2. Stacks
A stack is a sequence of items that are
accessible at only one end of the sequence.
Stacks 2
3. Pushing/Popping a Stack
Because a pop removes the item last added to
the stack, we say that a stack has LIFO (last-in/
first-out) ordering.
Stacks 3
4. TOP – THE MOST RECENTLY INSERTED
ITEM
PUSH - TO INSERT ONTO THE TOP OF A
STACK
POP - TO REMOVE THE TOP ITEM IN A
STACK
Stacks 4
5. Stack Implementations
Stacks 5
Array based
Where is top?
How are elements added, removed?
Linked List based
Where is top?
How are elements added, removed?
Efficiency of operations
6. Array Based Stack Implementation
Where should top be?
Stacks 6
12
15
5
2
3
4
stack
[0] array
What are array values?
s.push (20)
s.pop( )
7. Linked List Implementation
Stacks 7
D
C
B
t o p
A
S t a c k
D C B A
L i n k e d L i s t
f r o n t
s.push (‘F’)
s.pop( )
8. Stack with a Singly Linked List
We can implement a stack with a singly linked list
The top element is stored at the first node of the list
The space used is O(n) and each operation of the Stack ADT
takes O(1) time
t Æ
Stacks 8
nodes
elements