DS - Lecture 05 - Stacks
DS - Lecture 05 - Stacks
(CS3501)
DATA STRUCTURES
A K Dudyala
2
NITP -- CS3501
STACKS
A K Dudyala
3
NITP -- CS3501
UNIT IV: Stacks
Basics of Stack data structure, Implementation of stack using array and linked list,
Operations on stacks, Applications of Stacks, Notations – infix, prefix and postfix,
Conversion and evaluation of arithmetic expressions using Stacks.
A K Dudyala
4
NITP -- CS3501
Data structure-stack [5]
[4]
• Stack is a linear data structure in which the insertion and deletion operations are
[3]
performed at only one end.
[2]
• In a stack, adding and removing of elements are performed at a single position which [1]
is known as "top”. [0] top (presently)
• That means, a new element is added at top of the stack and an element is removed
from the top of the stack.
D->C->B->A
• Inserting an element into stack at top is said to be PUSH operation.
The order in
top D which elements
• Deleting element from top of the stack is said to be POP operation.
gets removed
C from the stack
• In stack, the insertion and deletion operations are performed based on LIFO (Last In Disk-A
Disk-B B
First Out) principle or FILO (First in Last Out) Disk-C
Disk-D A
A K Dudyala
5
NITP -- CS3501
Example of inserting elements into stack (PUSH operation)
Insert the elements 10,45,12,16,35 and 50 into an empty stack
top 16
top 12 12
top 45 45 45
10 10 10 10
top
top
top 50
top 35 35
16 16
12 12
45 45
Inserting (push)
10 10 A K Dudyala
6
NITP -- CS3501
Example of Removing elements from the stack (POP operation)
Deleted elements { } Deleted elements {50 , 35, 16, 12}
Deleted elements {50 , 35, 16, 12, 45}
Deleted elements {50}
Deleted elements {50 , 35, 16, 12, 45, 10}
Deleted elements {50, 35}
Deleted elements {50 , 35, 16}
top 50
35 top 35
16 16 top 16
12 12 12 top 12
45 45 45 top 45
45
10 10 10 10 top 10
10
top
In stack, the insertion and deletion operations are performed based on LIFO (Last In First Out) principle.
A K Dudyala
7
NITP -- CS3501
Application of stack (Importance of stack)
When a function call is invoked, calling function will be pushed onto the stack. It will
remain in the stack until called function finishes. GHI() DEF
{ ABC
When a function main calls
…..
function ABC, then main is main
…
inserted onto the top of stack. DEF()
ABC }
main will be removed once {
ABC is completed main …..
After GHI execution is
…
int main() main ABC() completed, DEF will be
GHI();
{ { removed from the top of
}
….. DEF(); stack.
… }
ABC(); ABC
….
… main
main
}
A K Dudyala
8
NITP -- CS3501
Stack Operations
• Standard operations
• Push
• To insert an element at the top of stack
• Pop
• To remove element from the top of stack
A K Dudyala
9
NITP -- CS3501
Applications of STACK
• Reversing a list
• Parentheses checking
• Recursion
• Tower of Hanoi
• DFS technique
A K Dudyala
10
NITP -- CS3501
Implementation of Stack
A K Dudyala
11
NITP -- CS3501
Implementation of STACK using Arrays
A K Dudyala
12
NITP -- CS3501
STACK ADT (Array Based)
// Define the stack
#define MAX 100
Element Type stack[MAX];
int top = -1;
A K Dudyala
13
NITP -- CS3501
Push operation
step - 1 : IF top = Max-1
PUSH(Element Type *stack, int top, Element Type value) Display “ OVERFLOW”
Go to step-4
step – 2: top++
• push() is a function used to insert an element into the stack. Step – 3: stack[top] = value
Step - 4: End
• The new element is always inserted at top position.
A K Dudyala
14
NITP -- CS3501
step - 1 : IF top = Max-1
Display “ OVERFLOW” Insert 20,45,12,16, and 35
Go to step-4
step – 2: top++ Push(stack, top, 20) Push(stack, top, 45) Push(stack, top, 12)
Step – 3: stack[top] = value
Step - 4: End
A K Dudyala
20
NITP -- CS3501
Implementation of STACK using Linked Lists
• The other way of implementing the stack is using the Linked List (SLL/ CSLL/
DLL/ CDLL).
• The push operation is the insertion of node into the linked list at the beginning.
• The pop operation is the deletion of node from the beginning (the header/ top
node)
A K Dudyala
21
NITP -- CS3501
STACK ADT (Linked List Based (SLL))
// Define node
typedef struct Node STACK;
struct Node
{ int data; // Assume we are storing integer data
STACK *next;
}*top = NULL; // Initially stack is empty
// Define the set of operations on stack
void push(STACK *, int);
int pop(STACK *);
void Display(STACK *)
int Peak(STACK *);
A K Dudyala
22
NITP -- CS3501
Push operation
Time Complexity = O(1)
PUSH(STACK *stack, int top, Element Type value)
• The new element is always inserted at the beginning of the list and is pointed by top
(In List it is head / start) .
• Step 1 - create a new_node. If new_node creation failed, then display "Stack OVERFLOW!!!
Insertion is not possible!!!" and terminate the function.
• Step 2 - If stack is NOT FULL, then insert the value and assign NULL to new_nodenext.
• Step 3 – if top == NULL, then assign new_node to top and terminate the function;
• Step 4 – If top != NULL, then assign top to new_nodenext and new_node to top;
A K Dudyala
23
NITP -- CS3501
PUSH(STACK *top, int value) new_node
new_node 10 NULL
1. new_nodenext=top
step1
x1000 x2000 x1000
x1000
// No Stack Overflow top 2. top=new_node
step4 x2000 20 x3000
new_node
x500 x2000
step 2 10 NULL x1000
30 NULL
top
x500 NULL x3000
step3
top new_node
x500 NULL 10 NULL
x1000
x1000
A K Dudyala 24
NITP -- CS3501
STACK OPERATION - PUSH (Logic)
A K Dudyala
25
NITP -- CS3501
Pop operation
POP(STACK *top)
Time Complexity = O(1)
• pop() is a function used to delete an element from the top of the stack.
• The element is always deleted at the beginning of the list and is pointed by top
(In List it is head / start) .
• Step 2 - If stack is NOT EMPTY, then declare a pointer temp and assign top to temp.
• Step 3 – if topnext == NULL, then assign NULL to top, delete the temp and terminate the
function;
• Step 4 – If topnext != NULL, then assign tempnext to top and delete temp;
A K Dudyala
26
NITP -- CS3501
POP(STACK *top)
top
step1 // Display Stack Underflow
NULL
x500
top
top x2000 20 x3000
step 2 x2000 step 4
30 NULL x500
x2000
x500 x2000 temp
temp
30 NULL
x3000
top top
X3000 30 NULL
step3 NULL
x500 x3000
x500
A K Dudyala 27
NITP -- CS3501
STACK OPERATION - POP (Logic)
A K Dudyala
28
NITP -- CS3501
STACK OPERATIONS (Logic)
• if char is „(„ or „{„ or „[„ then we push it onto the top of stack.
• If char is „)‟ or „}‟ or „]‟ then we perform pop operation and if the popped character
matches with the starting bracket then fine otherwise parenthesis are not balanced and
A K Dudyala
30
NITP -- CS3501
ASSIGNMENT (Graded one)
1. Write the algorithm/pseudo code to implement stack using doubly linked list.
2. Demonstrate how to check the balancing of the following parenthesis expressions using stack
i. (a+b*(c/d)+e*(-f))
ii. a[(b*(c+d))]
iii. a/(b/(c)
3. Write the algorithm/pseudo code for how to reverse the given string using the stack operations push
and pop. Also demonstrate with an example.
4. Write the algorithm/pseudo code to convert the given decimal number into binary using the stack.
Also demonstrate with an example.
5. Write the algorithm/pseudo code to check the given string is palindrome or not using stack. Also
demonstrate with an example.
A K Dudyala
31
NITP -- CS3501
Notations – infix, prefix and postfix
• Any arithmetic expression consists of operators and operands.
• There are three different notations used to write the arithmetic expression.
1. Infix Expression
2. Prefix Expression
3. Postfix expression
A K Dudyala
32
NITP -- CS3501
Infix Notation
• An expression is said to be in infix notation if the operators in the expression are placed in
between the operands on which the operator works.
• For example - a + b * c
• In the above example the operator is * is placed between the operands on which this
operator works, here b and c.
• Infix expressions are easy for humans to read, write and understand, but it is not the case
for computing devices.
• It is costly (in terms of space and time) to process the infix expressions in algorithms.
A K Dudyala
33
NITP -- CS3501
Prefix Notation
• An expression is said to be in prefix notation if the operators in the expression are
placed before the operands on which the operator works.
• In the above example the operator is * is placed before the operands on which this
operator works, here b and c, similarly the + is placed before a and the result of
(b*c).
A K Dudyala
34
NITP -- CS3501
Postfix Notation
• An expression is said to be in postfix notation if the operators in the expression are
placed after the operands on which the operator works.
• In the above example the operator is * is placed after the operands on which this
operator works, here b and c, similarly the + is placed after a and the result of
(b*c).
A K Dudyala
35
NITP -- CS3501
Evaluation of expressions
• When evaluating the arithmetic expression two things need be considered:
1. The precedence of the operator - If any operand is present in-between two different operators, the
precedence (priority) of the one operator over the other decides which operator should use the operand first
or which operator to be evaluated first. For example in the arithmetic expression a + b * c the operand b is
surrounded by the operators * and +. In computer languages the * enjoying the higher precedence than the +,
so * takes b first.
2. The Associativity of the operator - It resolves the ties between the same precedence of operators in the
arithmetic expression, by considering whether the operators are evaluated from left to right or right to left.
For example in the expression a* b * c, here b is surrounded by two * operators, So which * should take b
first or which multiplication must be done first? It is decided by the associativity of *. So in computer
languages * is a left associative, so the first * will be performed first (multiply a and b first then the result
will be multiplied by c).
• It is not advantageous to evaluate the infix expressions, so first convert them to postfix or prefix
and then compute the expressions.
A K Dudyala
36
NITP -- CS3501
Precedence and Associativity of operators
Operator Description Associativity Precedence
() Parenthesis 1(function calls) Left to Right 14
[] Brackets (array subscript)
. Members selection via object name
Member selection via pointer
++ -- Post increment and post decrement
++ -- Pre increment and pre decrement Right to Left 13
+ - Unary plus or minus
! ~ Logical negation and bitwise complement
(type) Casting type
* Dereference
& Address
Sizeof Size in bytes
* / % Arithmetic multiplication, division, modulus Left to Right 12
+ - Arithmetic addition, subtraction Left to Right 11
<< >> Bitwise shift left, shift right Left to Right 10
< <= Relational less than, less than or equal to Left to Right 9
> >= Relational greater than, greater than or equal to
1. Parenthesis are used to override the precedence of operators and such parenthesis expressions can be nested and evaluated from inner to outer
A K Dudyala
37
NITP -- CS3501
Precedence and Associativity of operators
Operator Description Associativity Precedence
== != Relational equal to, not equal to Left to Right 8
& Bitwise AND Left to Right 7
^ Bitwise Exclusive OR Left to Right 6
| Bitwise Inclusive OR Left to Right 5
&& Logical AND Left to Right 4
|| Logical OR Left to Right 3
?: Ternary condition Right to Left 2
= Assignment Right to Left 1
+= -+ Addition/Subtraction Assignment
*= /= Multiplication/Division Assignment
%= &= Modulus/Bitwise AND assignment
^= |= Bitwise Exclusive/ Inclusive Assignment
<<= >>= Bitwise Shift Left/Right Assignment
, Comma Left to Right 0
1. Parenthesis are used to override the precedence of operators and such parenthesis expressions can be nested and evaluated from inner to outer
A K Dudyala
38
NITP -- CS3501
Infix to postfix Conversion
1. Read all the symbols one by one from left to right in the given Infix Expression.
3. If the reading symbol is left parenthesis '(', then Push it on to the Stack.
4. If the reading symbol is right parenthesis ')', then Pop all the contents of stack until
respective left parenthesis is popped and print each popped symbol to the output.
5. If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However,
first pop the operators which are already on the stack that have higher or equal precedence
than the current operator and output them. If open parenthesis is there on top of the stack
then push the operator into stack, even though the precedence of ( is more than any other
operator and it is the exceptional case.
6. If the input is over, so pop all the remaining symbols from the stack and output them.
A K Dudyala
39
NITP -- CS3501
Infix to postfix Conversion (Example)
Consider the infix arithmetic expression: a * (b + c + d)
1 Input (infix expression)
a * (b + c + d) a
Output (postfix expression)
a is an operand
Action - Output a
top STACK
top (
• ( is an open parenthesis *
top *
• Action - push it into
stack STACK STACK
4
Input (infix expression)
a * (b + c + d) ab
A K Dudyala
41
NITP -- CS3501
Infix to postfix Conversion (Example)
Input (infix expression)
5
a * (b + c + d) a b
• + is an operator, Output (postfix expression)
• Action - push it into stack after removing top +
the higher or equal priority operators from (
the top of the stack. Present operator on *
stack is ( and it has higher precedence than
+, but for ( we have exception, so push + STACK
into stack,
6 abc
Input (infix expression) top +
Output (postfix expression)
a * (b + c + d) (
*
A K Dudyala
42
NITP -- CS3501
Infix to postfix Conversion (Example)
Input (infix expression)
7 a bc+
a * (b + c + d)
• + is an operator, top + Output (postfix expression)
• Action - push it into stack after removing (
the higher or equal priority operators top (
*
from the top of the stack. Present *
operator on stack is + and it has equal STACK
precedence with the input symbol +, so STACK
pop the + from stack and output.
abc +
a * (b + c + d) abc+d+
A K Dudyala
44
NITP -- CS3501
10 Infix to Postfix Conversion (Example)
Input (infix expression)
a * (b + c + d) a bc+ d+*
top STACK
A K Dudyala
45
NITP -- CS3501
Infix to Postfix conversion (Logic) void push(char *stack, int top, char e)
{
#include<stdio.h> if(top==size-1)
int prio(char op)
#include<string.h> printf("\n stack overflow");
{
#include<ctype.h> if(op = = '+‟ || op= = '-') else
return 1;
stack[++top]=e;
#define size 100 if(op = = '*' || op = = „/‟ || op==„%‟)
char stack[size]; return 2; }
if(op == „(„ )
int top=-1; return 0; char pop(char *stack, int top)
void push(char *, int, char); else {printf(“Wrong operator”); exit(0);} {
}
char pop(char *, int); // Assume our expression contains only these operators if(top==-1)
int prio(char op); printf("\n stack is underflow");
else
return stack[top--];
}
A K Dudyala
46
NITP -- CS3501
Infix to Postfix conversion (Logic)
void main()
{ char ie[100], pe[100]; int i, j=0;
printf("\n Enter infix expression: "); gets(ie);
for(i=0; ie[i]!='\0‟; i++)
{ if(ie[i]=='(„) push(ie[i]); // open parenthesis is pushed into the stack
else if( (ie[i] >= „a‟ && ie[i] <= „z‟) || (ie[i] >= „0‟ && ie[i] <= „9‟)) {pe[j++]=ie[i]; } //operand
else if(ie[i]==„)‟) // if it is closed parenthesis then pop all symbols from the stack upto open parenthesis encountered in the stack
{while(stack[top]!=„(„) { pe[j++]=pop(stack, top); } // Assume the given infix expression is parenthesis balanced one
pop(); }
else // if it is an operator
{ while(top > -1 && (prio(stack[top])>=prio(ie[i]) ) {pe[j++]=pop();}
push(ie[i]); }
}
while(top>-1) {pe[j++]=pop(); } // Leftover symbols from the stack are popped
pe[j]='\0‟;
printf("the infix expression %s converted to %s postfix expression",ie, pe);
}
A K Dudyala
47
NITP -- CS3501
Infix to Prefix Conversion
1. Reverse the given infix expression, for example the reverse of the infix expression a + b *c
is c * b + a. When reversing the parenthesis „)‟ will become „(„ and „(„ will become „)‟
(applicable to all types of brackets)
2. Apply the infix to postfix conversion algorithm on the reversed infix expression. For the
above example the resultant postfix expression is: cb*a+
3. Reverse the obtained postfix expression, and is the required prefix expression for the given
infix expression. For the above example, the infix expression is +a*bc
A K Dudyala
48
NITP -- CS3501
Prefix to Infix Conversion
1. Reverse the given prefix expression, for example the reverse of the prefix expression *cd is
dc*
2. Read the character by character of the reversed prefix expression and repeat the step 3 and 4
till there are no characters in the reversed prefix expression .
3. If the character read is an operand then push the operand into the stack. (push d and c)
4. If the character read is an operator, op, then pop the top two symbols from the stack, the
first one is p1, and the second one is p2. Push the concatenated string p1 op p2 to stack.
(push c *d )
5. Now the value in the stack is the required infix expression. (c*d)
A K Dudyala
49
NITP -- CS3501
Prefix to Postfix Conversion
1. Reverse the given prefix expression, for example the reverse of the prefix expression *cd is
cd*.
2. Read the character by character of the reversed prefix expression and repeat the step 3 and 4
till there are no characters in the reversed prefix expression .
3. If the character read is an operand then push the operand into the stack. (push d and c)
4. If the character read is an operator, op, then pop the top two symbols from the stack, the
first one is p1, and the second one is p2. Push the concatenated string p1 p2 op to stack.
(push c d * )
A K Dudyala
50
NITP -- CS3501
Postfix to Infix Conversion
1. Read the character by character of the given postfix expression and repeat the step 3 and 4
till there are no characters in the postfix expression. For example assume the postfix
expression ab+;
2. If the character read is an operand then push the operand into the stack. (push a and b)
3. If the character read is an operator, op, then pop the top two symbols from the stack, the
first one is p1, and the second one is p2. Push the concatenated string p2 op p1 to stack.
(push a * b )
A K Dudyala
51
NITP -- CS3501
Postfix to Prefix Conversion
1. Read the character by character of the given postfix expression and repeat the step 2 and 3
till there are no characters in the postfix expression. For example assume the postfix
expression ab+;
2. If the character read is an operand then push the operand into the stack. (push a and b)
3. If the character read is an operator, op, then pop the top two symbols from the stack, the
first one is p1, and the second one is p2. Push the concatenated string op p2 p1 to stack.
(push a * b )
4. Now the value in the stack is the required postfix expression. (*a b)
A K Dudyala
52
NITP -- CS3501
Examples
S.No Infix Expression Prefix Expression Postfix Expression
1 a+b*c +a*bc a b c*+
2 (a + b) * (c + d) * + a b + c d ab+cd+*
3 a*b + c * d +*ab*cd ab*cd*+
4 a+b+c+d +++abcd ab+c+d+
5 (a + b) * c – d -*+a b c d ab + c * d-
6 a+b-c -+a b c ab + c -
A K Dudyala
53
NITP -- CS3501
Evaluation of Postfix Expression
Infix exp: ( 5 + 3 ) * ( 8 -2)
Postfix: 5 3 + 8 2 - *
Algorithm
1. Scan the symbols one by one from left to right in the given Postfix Expression
3. If the reading symbol is binary operator (+ , - , * , / etc.,), then perform two pop operations and
do the operation specified by the reading symbol (if it is * do multiplication, etc) using the two
popped operands and push the result back on to the stack.
5. Finally! perform a pop operation and display the popped value as final result.
A K Dudyala
54
NITP -- CS3501
Evaluations of postfix Conversion (Example)
Infix exp: ( 6 + 2 ) * ( 8 - 2)
Postfix: 6 2 + 8 2 - *
Reading Stack
Reading Stack Reading Stack Symbol
Symbol Symbol
8
Initially 2 (operand) t
(operand) t o 8
o 2 push(stack, top, 8) p
push(stack, top, 2) p
8
6
t
o
p
+ 2 t
(operator) (operand) o 2
p
6 pop the top two push(stack, top, 2) 8
(operand) two operands from
push(stack, top, 6) t Stack t 8
o
6 op1 = pop(stack, top) //2
o 8
p p
op2 = pop(stack, top) // 6
op3 = op2 + op1 // 8
push(op3)
A K Dudyala
55
NITP -- CS3501
Evaluations of postfix Conversion (Example)
Infix exp: ( 6 + 2 ) * ( 8 - 2)
Postfix: 6 2 + 8 2 - *
Reading Stack
Symbol
-
(operator)
pop the top two
two operands from stack t
*
(operator)
pop the top two
operands from stack
op1 = pop(stack, top) // 6
t
op2 = pop(stack, top // 8 o 48
op3 = op2 * op1 p
push(op3)
A K Dudyala
56
NITP -- CS3501
#include<stdio.h>
#include<string.h>
Postfix Evaluation void push(int e)
#include<ctype.h> {
#define size 100 If(top==size-1)
else if( isdigit(pe[i])) printf("\n stack overflow");
int stack[size];
push(pe[i]-'0'); else
int top=-1;
else stack[++top]=e;
void push(int);
{ op2=pop(); }
int pop();
op1=pop();
void main() switch(pe[i])
{ char pe[30]; int pop()
{case '+‘ : push(op1+op2);break;
int i,v,op1,op2; {
case '-‘ : push(op1-op2);break;
printf("\n enter any if(top==-1)
case '*‘ : push(op1*op2);break;
postfix expression"); printf("\n stack underflow");
case '/': push(op1/op2);break;
gets(pe); else
case '%‘ : push(op1%op2);break;
for(i=0;pe[i]!='\0';i++) return stack[top--];
default: printf("\n invalid operation");
{ if(isalpha(pe[i])) }
}
{printf("\n enter value for %c", pe[i]); }
scanf("%d",&v); }
push(v); printf(“\n The result is: %d",stack[top]);
} Postfix: X 4 + Y Z - *
}
X= 5, Y=8, Z=2
A K Dudyala
57
NITP -- CS3501
Thank You
A K Dudyala
58
NITP -- CS3501