Chapter 4 - Stack
Chapter 4 - Stack
DIT 2014
Chapter 4 :
Stack
Shazana Md Zin, FTMM (2010)
2
What is Stack?
3
Stack related term
• A memory portion, which is used for storing the elements.
• Based on principle of Last-In-First-Out (LIFO).
• TOP – the pointer points to the top element in the stack.
• Stack Underflow – there is no element in the stack.
• Stack Overflow – the stack contains equal or no more
elements to be added.
• PUSH – inserting new element to the top of the stack.
• POP – removing one element from the top of the stack.
4
Introduction
5
Introduction
6
Introduction
7
Basic Stack Operations
8
9
Process
Example:
Push books
Red Book
Blue Book
Green Book
Yellow Book
Pop books
Yellow Book
Green Book
Blue Book
Red Book
10
Stack Operation
Create Stack
size = 4
3
2
1
0
top = -1
11
Stack Operation
Make sure the stack is empty@not – before ‘pop’
If ‘0’ => cannot ‘pop’
3
2
1
0
top =-1
12
Stack Operation
Make sure the stack is empty@not – before ‘push’
If stack is full => cannot ‘push’
3
2
1
0
top = 3
13
Stack Operation
Push data into the stack
If stack ≠ full => ‘push’ to add a node
3
2
1
0
top -1
1
0
3
2
top
14
Stack Operation
Pop data from the stack
If stack ≠ empty => ‘pop’ to remove a node
3
2
1
0
top -1
1
2
0
3
top
Stack Array Implementation
Struct Declaration
2
void create(stack *t)
{ 1
t->top = -1; -1 0
}
top list
Overflow and Underflow Controller