4.1Stack with an Array
Push: adding an element
push puts a new element on top of a stack. On an array stack it takes three short steps: check that there is room, move top up by one, write the value into that cell. In this lesson you see the three steps and what happens when the array is full.
- Why push checks for a full stack first
- Why top is incremented before the value is written
- How C, Java and Python behave when you push onto a full stack
1Idea
top is the index of the top element. The new element goes into the cell just to its right. So top is incremented first, then the value is written to items[top]. No element is shifted.
But the array has a fixed size. If top is already at the last cell (CAPACITY - 1), there is no room to write. This is called an overflow. That is why push starts with the isFull check.
How the overflow is reported depends on the language. In C the function returns false and the stack is unchanged. Java throws an IllegalStateException and Python raises an IndexError.
2Step by step
The drawing first pushes 5 onto a stack holding 3 and 8. Then the stack is filled up and one more push is tried.
- Start. The stack holds 3 and 8, and
topis 1. isFullis checked:topis 1 and the last index is 4. There is room, so we go on.topis incremented to 2. It now marks cell 2, which is still empty.- The value is written to
items[2]. 5 is now on top of the stack. - The C version returns true. The push is done; no other element was touched.
- 6 and 9 were pushed too.
topis 4: every cell is used. - push(7) is tried.
isFullreturns true and 7 is not written. C returns false, Java and Python throw an error.topstays at 4.
#define CAPACITY 5 struct Stack { int items[CAPACITY]; int top;}; void create(struct Stack* s) { s->top = -1;} bool isFull(struct Stack* s) { return s->top == CAPACITY - 1;} bool push(struct Stack* s, int value) { if (isFull(s)) { return false; // overflow } s->top++; s->items[s->top] = value; return true;}class ArrayStack { int[] items; int top = -1; ArrayStack(int capacity) { items = new int[capacity]; } boolean isFull() { return top == items.length - 1; } void push(int value) { if (isFull()) { throw new IllegalStateException("stack is full"); } top++; items[top] = value; }}class ArrayStack: def __init__(self, capacity): self.items = [None] * capacity self.top = -1 def is_full(self): return self.top == len(self.items) - 1 def push(self, value): if self.is_full(): raise IndexError("stack is full") self.top += 1 self.items[self.top] = valueThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
One comparison, one increment and one write. The number of elements in the stack does not matter.
The room is already set aside in the array; push asks for no new memory.
This is the same as inserting at the end of an array: the end of the array is the top of the stack. Inserting at the front would shift everything, which is why the top is kept at the end of the array.
4Common mistake
The most common mistake is forgetting the full check:
s->top++;s->items[s->top] = value; // no checkOn a full stack top becomes 5 and the value is written past the end of the array. C does not stop this; it silently corrupts the memory next to it. In Java you get an ArrayIndexOutOfBoundsException, but top has already moved. Check first, then write. Another mistake is writing items[top++] instead of items[++top]: the value lands on top of the old top element.
5Try it
You push 1, 2 and 3, in that order, onto an empty stack with capacity 5. What is top, and which cell holds 3?
The answer is B. top starts at -1 and goes up by one with each push: 0, 1, 2. The last value, 3, is in items[2]; the top is at the end of the array.
Show the answer
The answer is B. top starts at -1 and goes up by one with each push: 0, 1, 2. The last value, 3, is in items[2]; the top is at the end of the array.
If push swaps its two lines (items[top] = value first, then top++), what happens?
The answer is B. The write happens while top still marks the old top, so the old top is lost. On an empty stack it even tries to write to items[-1]. The right order is increment first, then write.
Show the answer
The answer is B. The write happens while top still marks the old top, so the old top is lost. On an empty stack it even tries to write to items[-1]. The right order is increment first, then write.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.