algoritmauzmanı
Sign in
TREN
4.1Stack with an Array
Lesson 4.1.3

Pop: removing an element

removes the top element of a and returns it. The last element in is the first one out; this operation is where the order shows. On an array stack, pop is the reverse of push: first the value is read, then goes down by one.

What you will learn
  • Why pop checks for an empty stack first
  • Why the value is read before top is decremented
  • Why the removed value stays in the cell but no longer belongs to the stack
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

The top element is in items[top]. Pop copies this value into a variable, then decrements top. The element below becomes the new top. No element is shifted.

If the stack is empty (top == -1) there is nothing to read. This is called a stack . That is why pop starts with the isEmpty check. In C the function returns false; Java throws an IllegalStateException and Python raises an IndexError.

In C the return value reports success, so the removed value is handed back through a : int* value. In Java and Python the value is simply returned.

Pop does not erase the cell. The removed value is still in the array, but it sits above top, so it is no longer part of the stack. The next push writes over it.

2Step by step

The drawing pops 5 from a stack holding 3, 8 and 5. Then the stack is emptied and one more pop is tried. Faded cells do not belong to the stack.

30815234-1top1top2top5value3valuetop
  1. Start. The stack holds 3, 8 and 5, and top is 2. 5 is on top.
  2. isEmpty is checked: top is not -1. The stack is not empty, so we go on.
  3. The top value is read: value = items[2], which is 5.
  4. top is decremented to 1. 5 is still in the cell but no longer in the stack; the new top is 8.
  5. 5 is returned. In C it was written to *value and the function returns true.
  6. Two more pops: first 8, then 3 came out. top is -1 and the stack is empty. The values are still in the cells.
  7. One more pop is tried. isEmpty returns true: underflow. C returns false, Java and Python throw an error. top stays at -1.

#define CAPACITY 5 struct Stack {    int items[CAPACITY];    int top;}; void create(struct Stack* s) {    s->top = -1;} bool isEmpty(struct Stack* s) {    return s->top == -1;} bool pop(struct Stack* s, int* value) {    if (isEmpty(s)) {        return false;  // underflow    }    *value = s->items[s->top];    s->top--;    return true;}
class ArrayStack {    int[] items;    int top = -1;     ArrayStack(int capacity) {        items = new int[capacity];    }     boolean isEmpty() {        return top == -1;    }     int pop() {        if (isEmpty()) {            throw new IllegalStateException("stack is empty");        }        int value = items[top];        top--;        return value;    }}
class ArrayStack:    def __init__(self, capacity):        self.items = [None] * capacity        self.top = -1     def is_empty(self):        return self.top == -1     def pop(self):        if self.is_empty():            raise IndexError("stack is empty")        value = self.items[self.top]        self.top -= 1        return value

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(1)

One comparison, one read and one decrement. It does not depend on the number of elements.

Memory
O(1)

Only one variable is used, to hold the removed value.

This is the same as deleting from the end of an array. Because the top is kept at the end of the array, pop never shifts an element.

4Common mistake

A common mistake is swapping the two lines:

s->top--;*value = s->items[s->top];  // wrong: reads the element below

If top is decremented first, the value read is not the top element but the one below it. Even a single pop returns the wrong value, and on a one-element stack it reads items[-1]. Read first, then decrement. Another mistake is skipping the empty check: popping an empty stack sets top to -2 and breaks the stack.

5Try it

You push 4, 7 and 1 onto an empty stack, then pop twice. Which values do the pops return?

Show the answer

The answer is B. A stack works : 1, pushed last, comes out first, then 7 below it. 4 stays in the stack and becomes the new top.

items = [3, 8, 5, _, _] and top = 2. After one pop, what do the array and top look like?

Show the answer

The answer is B. Pop does not clear the cell; it only decrements top. 5 stays in the array, but it is above top, so it does not belong to the stack.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.