Professional Documents
Culture Documents
DS - Lecture 05 - Stacks
DS - Lecture 05 - Stacks
(CS3401)
DATA STRUCTURES
Dr Somaraju Suvvari
2
NITP -- CS3401
STACKS
Dr Somaraju Suvvari
3
NITP -- CS3401
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.
Dr Somaraju Suvvari 4
NITP -- CS3401
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 [1]
[0] top (presently)
which is known as "top”.
• That means, a new element is added at top of the stack and an element is removed
top 16
top 12 12
45 45 45
top
10 10 10 10
top
top
50
top
top 35 35
16 16
12 12
45 45 Inserting (push)
10 10 Dr Somaraju Suvvari 6
NITP -- CS3401
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 12
top
45 45 45 45 top 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. Dr Somaraju Suvvari 7
NITP -- CS3401
Application of stack (Importance of stack)
When a function call is invoked, calling function will be pushed onto the stack. It will be
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
… completed, DEF will be
int main() main ABC() GHI(); removed from the top of
{ { }
….. DEF(); stack.
… }
ABC(); ABC
….
main
…
main
}
Dr Somaraju Suvvari 8
NITP -- CS3401
Stack Operations
• Standard operations
• Push
• To insert an element at the top of stack
• Pop
• To remove element from the top of stack
• Parentheses checking
• Recursion
• Tower of Hanoi
• DFS technique
Dr Somaraju Suvvari 10
NITP -- CS3401
Implementation of Stack
Dr Somaraju Suvvari 11
NITP -- CS3401
Implementation of STACK using Arrays
Dr Somaraju Suvvari
12
NITP -- CS3401
STACK ADT (Array Based)
// Define the stack
#define MAX 100
Element Type stack[MAX];
int top = -1;
Dr Somaraju Suvvari 13
NITP -- CS3401
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.
Dr Somaraju Suvvari 14
NITP -- CS3401
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
Dr Somaraju Suvvari 16
NITP -- CS3401
step - 1 : IF top = -1 Deleted elements { } pop(stack, top) pop(stack, top) pop(stack, top)
Display “ UNDERFLOW” Deleted elements {35} Deleted elements {35, 16} Deleted elements {35, 16, 12}
Go to step-6
step – 2: x = stack[top]
Step – 4: top-- top 35 [4]
Step – 5: return x 16 [3] [3]
Step - 6: End top 16
12 [2] 12 [2] top 12 [2]
45 [1] 45 [1] 45 [1] top 45 [1]
int pop(int *stack, int top)
10 [0] 10 [0] 10 10
{ int val; [0] [0]
pop(stack, top) pop(stack, top)
if(top = = -1) Deleted elements {35, 16, 12, 45} Deleted elements {35, 16, 12, 45, 10}
printf(“\n underflow\n”);
else pop(stack, top)
{ val=stack[top];
top=top-1;
return val;
} Underflow
top 10 [0]
} top
Dr Somaraju Suvvari
NITP -- CS3401 17
STACK PROGRAM
void main()
{ int value, choice, ele;
#include<stdio.h> while(1)
{ clrscr(); printf("\n\n***** MENU *****\n");
#include<conio.h> printf(“1. Push\n 2. Pop\n 3. Display\n 4. Peak 5.Exit");
#define SIZE 05 printf("\nEnter your choice: "); scanf("%d",&choice);
switch(choice)
int stack[SIZE], top = -1; {case 1: printf("Enter the value to be insert: ");
void push(int); scanf("%d",&value); push(value); break;
case 2: ele=pop(); printf(“\n %d is deleted”,ele); break;
int pop(); case 3: display(); break;
void display(); case 4: ele=peak(); printf(“\n The top element is: %d”, ele); break;
case 5: exit(0);
int peak() default: printf("\nWrong selection Try again!!!");
}// switch – case
}// while
} // main
Dr Somaraju Suvvari
18
NITP -- CS3401
STACK OPERATIONS (LOGIC)
int pop()
void push(int value) { int element;
{ if(top == SIZE-1) if(top == -1)
printf("\n Stack Overflow … “); printf("\n Stack Underflow”);
else else
{ top++; stack[top] = value; { element=stack[top]; top--;
printf("\n Insertion success!!!"); } return element; }
} }
int peak()
void display() { int val;
{ if(top == -1) if (top==-1) printf(“\n Stack Underflow”);
printf("\n Stack Underflow"); else
else { val=pop();
{ int i; push(val);
printf("\n Stack elements are:\n"); return val;
for(i=top; i>=0; i--) }
printf(“%d ", stack[i]); } }
} Time Complexity = O(1)
Time Complexity = O(n)
Dr Somaraju Suvvari 19
NITP -- CS3401
Implementation of STACK using Linked Lists
Dr Somaraju Suvvari
20
NITP -- CS3401
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)
Dr Somaraju Suvvari 21
NITP -- CS3401
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
Dr Somaraju Suvvari 22
NITP -- CS3401
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 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;
Dr Somaraju Suvvari 23
NITP -- CS3401
PUSH(STACK *top, int value)
10
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
10 NULL x1000 x500 x2000
step 2
30 NULL
top
x500 NULL x3000
step3
top new_node
x500 NULL 10 NULL
x1000
x1000
Dr Somaraju Suvvari 24
NITP -- CS3401
STACK OPERATION - PUSH (Logic)
Dr Somaraju Suvvari 25
NITP -- CS3401
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;
Dr Somaraju Suvvari 26
NITP -- CS3401
POP(STACK *top)
top
step1 NULL // Display Stack Underflow
x500
top
top x2000 20 x3000
step 2 x2000 30 NULL step 4
x500
x2000
x500 x2000
temp 30 NULL
x3000
top top
step3 NULL
X3000 30 NULL
x500 x3000
x500
Dr Somaraju Suvvari 27
NITP -- CS3401
STACK OPERATION - POP (Logic)
Dr Somaraju Suvvari 28
NITP -- CS3401
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 is the
matches with the starting bracket then fine otherwise parenthesis are not balanced and
Dr Somaraju Suvvari 30
NITP -- CS3401
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.
Dr Somaraju Suvvari 31
NITP -- CS3401
Notations – infix, prefix and postfix
• Any arthematic expression consists of operators and operands.
• There are three different notations used to write the athematic expression.
1. Infix Expression
2. Prefix Expression
3. Postfix expression
Dr Somaraju Suvvari 32
NITP -- CS3401
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.
Dr Somaraju Suvvari 33
NITP -- CS3401
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).
Dr Somaraju Suvvari 34
NITP -- CS3401
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).
2. The Associativity of the operator - It resolves the ties between the same precedence of operators in the
arithmetic expression, by considering the 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 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.
Dr Somaraju Suvvari
36
NITP -- CS3401
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
Dr Somaraju Suvvari 37
NITP -- CS3401
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 Dr Somaraju Suvvari
38
NITP -- CS3401
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.
Dr Somaraju Suvvari
39
NITP -- CS3401
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
Dr Somaraju Suvvari 41
NITP -- CS3401
Infix to postfix Conversion (Example)
Input (infix expression)
5
a * (b + c + d) a b
• + is an operator, Output (postfix expression)
top +
• Action - push it into stack after removing
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)
*
Dr Somaraju Suvvari 42
NITP -- CS3401
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 +
STACK
Dr Somaraju Suvvari 43
NITP -- CS3401
Infix to postfix Conversion (Example)
Input (infix expression)
8
a * (b + c + d) a bc+ d
a * (b + c + d) abc+d+
Dr Somaraju Suvvari 44
NITP -- CS3401
10 Infix to Postfix Conversion (Example)
Input (infix expression)
a * (b + c + d) a bc+ d+*
top STACK
Dr Somaraju Suvvari 45
NITP -- CS3401
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");
if(op = = '+’ || op= = '-') else
#include<ctype.h>
return 1;
#define size 100 if(op = = '*' || op = = ‘/’ || op==‘%’) stack[++top]=e;
return 2; }
char stack[size];
if(op == ‘(‘ )
int top=-1; return 0; char pop(char *stack, int top)
else {printf(“Wrong operator”); exit(0);} {
void push(char *, int, char);
}
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--];
}
Dr Somaraju Suvvari 46
NITP -- CS3401
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);
}
Dr Somaraju Suvvari 47
NITP -- CS3401
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
Dr Somaraju Suvvari
48
NITP -- CS3401
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 infix 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)
Dr Somaraju Suvvari
49
NITP -- CS3401
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 infix 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 * )
Dr Somaraju Suvvari
50
NITP -- CS3401
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 )
Dr Somaraju Suvvari
51
NITP -- CS3401
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)
Dr Somaraju Suvvari
52
NITP -- CS3401
Examples
Dr Somaraju Suvvari 53
NITP -- CS3401
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.
Dr Somaraju Suvvari
54
NITP -- CS3401
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
t
2 8
Initially
t o 8
(operand) o 2 p
push(stack, top, 2) p
(operand) 8
6 push(stack, top, 8)
t
o
p
+ t
o 2
p
(operator) 2
pop the top two 8
6 (operand)
two operands from 8
t t push(stack, top, 2)
(operand)
o
6 Stack o 8
p p
op1 = pop(stack, top) //2
push(stack, top, 6)
op2 = pop(stack, top) // 6
op3 = op2 + op1 // 8
push(op3)
Dr Somaraju Suvvari 55
NITP -- CS3401
Evaluations of postfix Conversion (Example)
Infix exp: ( 6 + 2 ) * ( 8 - 2)
Postfix: 6 2 + 8 2 - *
Reading Stack
Symbol
-
(operator)
pop the top two t
*
(operator)
pop the top two
operands from stack
t
op1 = pop(stack, top) // 6 o 48
op2 = pop(stack, top // 8 p
op3 = op2 * op1
push(op3)
Dr Somaraju Suvvari 56
NITP -- CS3401
#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
Thank You
Dr Somaraju Suvvari
58
NITP -- CS3401