Lecture 7
Lecture 7
PROGRAMMING II
Stack
Sherina Sally
D e p a r t m e n t o f I C T,
F a c u l t y o f Te c h n o l o g y,
University of Colombo
Introduction
• Last In First Out (LIFO) – The last element inserted will be removed first
1
04-Jul-23
Stack Operations
Stack Implementation
• array
• linked list
2
04-Jul-23
Stack Underflow
Stack Overflow
• Occurs when the TOP is a value larger than the maximum elements of the stack
3
04-Jul-23
• Implementation is simple
• A stack is FULL, if the number of elements has reached the maximum size
Push
• The first element pushed into the stack will be added to the bottom
4
04-Jul-23
Push … (2)
end procedure
Pop
• The top most element of the stack will be removed first
• After the pop operation, change the reference of the top most element
5
04-Jul-23
Pop … (2)
return data
end procedure
Department of ICT, Faculty of Technology, University of Colombo | [email protected]
Peek
top
6
04-Jul-23
Traverse
7
04-Jul-23
Push
• The head element is pushed first into the stack
• Create a node with a data value and a link pointing to NULL, Push
• After pushing, point the next link of the node to the HEAD node
Push … (2)
void push(int data){
if (head == NULL){
head=node;
} else{
node.next = head;
head= node;
}
}
Department of ICT, Faculty of Technology, University of Colombo | [email protected]
8
04-Jul-23
Pop
• The top most element of the stack will be removed first : HEAD node
• After the pop operation, change the HEAD to the next node in the
stack
Pop … (2)
int pop(){
if (head != NULL){
Node node = head;
head = head.next;
node.next = null;
return node.data;
}else{
return -1;
}
}
Department of ICT, Faculty of Technology, University of Colombo | [email protected]
9
04-Jul-23
Peek
int peek(){
HEAD top
if (head != NULL){
return head.data;
}else{
return -1;
}
}
Department of ICT, Faculty of Technology, University of Colombo | [email protected]
Traverse
10
04-Jul-23
push(A)
push(B)
push(C)
pop(C)
push(D)
peek()
Expression Evaluation
eg: 23 * 4, 50 / 6
eg: + 34 2, + 48 * 6 5
eg: 48 6 5 * +
Department of ICT, Faculty of Technology, University of Colombo | [email protected]
11
04-Jul-23
(2 + 3) * 9 / 5
Department of ICT, Faculty of Technology, University of Colombo | [email protected]
• Postfix notation : 23 + 9 * 5 /
push(2)
push(3)
3
2
pop(2) (2+3) = 5
pop(3)
push(5)
5
12
04-Jul-23
push(9)
9
5
pop(9) (9*5) = 45
pop(5)
push(result)
45
push(5)
5
45
pop(5) (45 / 5) = 9
pop(45)
push(result)
9
13
04-Jul-23
Exercise
1) 78 – 9 * 2
2) 34 + 10 / 5 – 2
14