Lecture 3
Stack
Stack
The Stack ADT (Abstract Data Type)
A Stack is a collection of objects inserted and removed according to the Last In First Out (LIFO) principle. Think of a stack of dishes.
Stack operations
Push and Pop are the two main operations
A lot of applications
Classic Example: Parenthesis checker
(2 + 3) - (4 + 1)
Implementation. Arrays
Main update methods:
Additional useful methods
reminder
Implementation design
|
|
|
X |
X |
Implementation design
|
|
|
X |
X |
top
Implementation design
|
|
|
X |
X |
top
push(2)
Implementation design
|
|
2 |
X |
X |
top
push(2)
Implementation design
|
|
2 |
X |
X |
top
push(2)
Implementation design
|
|
2 |
X |
X |
top
push(2)
push(5)
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
pop()
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
pop()
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
push(7)
Implementation design
|
7 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
push(7)
Implementation design
|
7 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
push(7)
push (int elem) {
stack[top]= elem;
top++;
}
stack
|
|
|
|
|
top = 0
top
Implementation design
|
7 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
push(7)
push (int elem) {
stack[top]= elem;
top++;
}
stack
|
|
|
|
|
top = 0
top
int pop() {
top --;
return stack[top];
}
Implementation design
|
|
|
X |
X |
Implementation design
|
|
|
X |
X |
top
Implementation design
|
|
|
X |
X |
top
push(2)
Implementation design
|
|
|
X |
X |
top
push(2)
Implementation design
|
|
2 |
X |
X |
top
push(2)
Implementation design
|
|
2 |
X |
X |
top
push(2)
push(5)
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
pop()
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
pop()
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
Implementation design
|
5 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
push(7)
Implementation design
|
7 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
push(7)
Implementation design
|
7 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
push(7)
push (int elem) {
top++;
stack[top]= elem;
}
stack
|
|
|
|
|
top = -1
top
Implementation design
|
7 |
2 |
X |
X |
top
push(2)
push(5)
pop() //5 is returned
push(7)
push (int elem) {
top++;
stack[top]= elem;
}
stack
|
|
|
|
|
top = 0
top
int pop() {
e = stack[top];
top --;
return e;
}
Complexity
Operation | Complexity |
Push | O(1) |
Pop | O(1) |
Advantage and Limitation
all operations are completed in one step. No loops are needed: O(1)
You have to know the upper bound of growth and allocate memory accordingly. If the array is full and there is another push operation then you encounter an exception (error).