ADT Stack
Idea Like You Are 10
A stack is like a pile of books.
You can:
- put a book on top
- remove a book from the top
But you cannot remove the book from the middle first.
This rule is called:
Stack ADT Operations
push(x): add item on toppop(): remove top itempeek()ortop(): see top itemisEmpty(): check if no items existisFull(): check if stack is full in array implementationdisplay(): show all items
Array Representation
If top = -1, the stack is empty.
Algorithms
Push
Time: O(1)
Pop
Time: O(1)
Peek
Time: O(1)
Is Empty
Time: O(1)
Is Full
Time: O(1)
Display
Time: O(n)
Complexity Analysis
| Operation | Time |
|---|---|
| Push | O(1) |
| Pop | O(1) |
| Peek | O(1) |
| Is Empty | O(1) |
| Is Full | O(1) |
| Display | O(n) |
Why These Complexities?
push,pop, andpeekonly touch the topdisplaymust visit every element
Space Complexity
- Array stack stores up to
nitems - total space is
O(n)
Advantages
- very simple
- fast insert and delete at one end
- useful in many algorithms
Disadvantages
- only one end is usable
- array stack has fixed size unless resized