Data Structures and
Algorithms
Module -3
Stack
Dr. R. Jothi, SCOPE
VIT Chennai
Outline
Stack
Operations of Stack
Array Implementation of stack
Applications
Balanced parentheses
Infix to postfix
Expression evaluation
Dr. R. Jothi, VIT Chennai
What is a stack?
It is an ordered group of homogeneous
items.
Stack principle: LAST IN FIRST OUT = LIFO
the last element inserted is the first one to be
removed
Only access to the stack is the top element
Consider trays in a cafeteria
to get the bottom tray out, you must first remove
all of the trays above
Dr. R. Jothi, VIT Chennai
Stack : Push()
Push operation places
a new item at the top
of the stack
Stack : Pop()
Pop operation removes
the next item from the
top of stack
Other Operations on Stack
IsEmpty() - reports whether the stack is empty or not
IsFull() - reports whether the stack is full or not
Top() – returns top element (but does not remove it)
Top sometimes called as peek()
InitStack() – initialization of stack
DestroyStack() – destroying the stack
Dr. R. Jothi, VIT Chennai
Example
Dr. R. Jothi, VIT Chennai
Stack Applications
Recursion handling
Expression evaluation
Infix to postfix notation
Parenthesis checking
Backtracking
Maze tracker
Undo
Recent tabs
Dr. R. Jothi, VIT Chennai
Stack Implementation
Array
Linked-list
Dr. R. Jothi, VIT Chennai
Stack Implementation using Array
We need to keep track of (at least) the array contents and
a top index.
How could we combine these 2 into a single C construct?
struct Stack{
int *contents;
int top;
int Maxsize;
};
Note that the contents is a pointer since it will be
dynamically-allocated
Dr. R. Jothi, VIT Chennai
InitStack()
struct Stack * InitStack(int k) {
This function will struct Stack *T;
set up a Stack T = (struct Stack*)malloc(sizeof(struct Stack));
structure so that T->top=-1;
it represents an T->Maxsize=k;
empty stack. T->contents=(int *)malloc(sizeof(int)*k);
printf("Empty stack created\n");
return T;
}
struct Stack *S=InitStack(5)
Dr. R. Jothi, VIT Chennai
InitStack()
struct Stack * InitStack(int k) {
struct Stack *T;
T = (struct Stack*)malloc(sizeof(struct Stack));
T->top=-1;
T->Maxsize=k;
T->contents=(int *)malloc(sizeof(int)*k);
printf("Empty stack created\n");
return T;
} top=-1
struct Stack *S=InitStack(5)
Dr. R. Jothi, VIT Chennai
Push()
void push(struct Stack *T, int x)
{
Called from if(IsFull(T))
main() {
push(S, 50); printf("Full! \n "); return;
}
#Write your code here: line-1 top 7
#Write your code here : line-2 6
}
Dr. R. Jothi, VIT Chennai
Push()
void push(struct Stack *T, int x)
{
if(IsFull(T))
push(S, 50); {
printf("Full! \n "); return;
}
T->top++; top 7
T->contents[T->top]=x; 6
}
Dr. R. Jothi, VIT Chennai
Push()
void push(struct Stack *T, int x)
{
if(IsFull(T))
push(S, 50); {
printf("Full! \n "); return;
top 50
}
T->top++; 7
T->contents[T->top]=x; 6
}
Dr. R. Jothi, VIT Chennai
Pop()
void pop(struct Stack *T)
pop(S); {
if(IsEmpty(T))
{
printf("empty! \n ");
top 50
return;
} 7
printf("Popped ele : %d\n",T->contents[T->top]); 6
T->top--;
}
Dr. R. Jothi, VIT Chennai
Pop()
void pop(struct Stack *T)
pop(S); {
if(IsEmpty(T))
{
printf("empty! \n ");
return; 50
} top 7
printf("Popped ele : %d\n",T->contents[T- 6
>top]);
T->top--;
}
Dr. R. Jothi, VIT Chennai
IsFull()
Condition for checking full stack?
top 99
23
int IsFull(struct Stack *T)
{ if(T->top==T->Maxsize-1) 45
return 1; 50
return 0; 7
} 6
Dr. R. Jothi, VIT Chennai
IsEmpty()
int IsEmpty(struct Stack *T)
{ if(T->top==-1)
return 1;
return 0;
}
Dr. R. Jothi, VIT Chennai
Top() or Peek()
int Top(struct Stack *T)
{
return(T->contents[T->top]);
}
Dr. R. Jothi, VIT Chennai
DisplayStack()
void displayStack(struct Stack *T)
{
int i;
printf("Stack : ");
for(i=0;i<=T->top;i++)
printf("%d ", T->contents[i]);
printf("\n");
}
Dr. R. Jothi, VIT Chennai
DestroyStack()
void destroyStack(struct Stack *T)
{
free(T->contents);
T->contents = NULL;
T->Maxsize = 0;
T->top = -1; /* I.e., empty */
}
Dr. R. Jothi, VIT Chennai
Stack Applications
Balancing parenthesis
Expression Evaluation
Infix, Prefix and Postfix Notations
Infix to Prefix and Postfix conversion
Postfix Evaluation
Recursive function Calls
Dr. R. Jothi, VIT Chennai
Balanced Parenthesis
For each left parenthesis, bracket,
braces, there is a corresponding
closing symbol
Symbols are appropriately nested
Dr. R. Jothi, VIT Chennai
Example-1 : { [ ( ) ] }
The contents of a stack during the scan of an expression that
contains the balanced delimiters (), [], {}
Dr. R. Jothi, VIT Chennai
Example -2 : { [ ( ] ) }
Dr. R. Jothi, VIT Chennai
Example-3: { [ ( ] ) }
Dr. R. Jothi, VIT Chennai
Algorithm
Assume balanced=true
While(balanced && ! End_of_string)
Read next_char
If next_char is left bracket push(next_char) and continue
If right bracket:
If empty_stack balanced=false; break ;
else {
x=pop(stack)
If x is counter_part of next_char then balanced=true else balanced=false }
If balanced==false, break from while else continue with next char
Dr. R. Jothi, VIT Chennai
Checking for Balanced (), [], {}
right symbol does not
have its counterpart
Left symbol does not
have its counterpart
Dr. R. Jothi, VIT Chennai
Expression notations
Infix expressions
Binary operators appear between operands
a+b a*b+c
Prefix expressions (polish)
Binary operators appear before operands
+ab +*abc
Postfix expressions (revere polish)
Binary operators appear after operands
ab+ ab*c+
Easier to process – no need for parentheses nor precedence
Dr. R. Jothi, VIT Chennai
Why to study these notations?
Postfix
No parenthesis, No operator precedence checking
Convenient for evaluating expressions on computer with stacks
Reflects the order in which operations are performed
Dr. R. Jothi, VIT Chennai
Expression in Source code Parse tree during compilation
ab+c*
Dr. R. Jothi, VIT Chennai
Dr. R. Jothi, VIT Chennai
Examples
Infix Prefix Postfix
a+b-c -+abc ab+c-
(A+B)*(C-D) *+AB–CD AB+CD-*
A/(B+C) /A+BC ABC+*/
X+Y/Z*A X+((Y/Z)*A) XYZ/A*+
X+(/YZ*A)
X+(*/YZA)
+X*/YZA
A*B^C+D ((A * (B ^ C) )+ D ABC^*D+
(A*(^BC))+D
+*A^BCD Dr. R. Jothi, VIT Chennai
Examples
Infix Prefix Postfix
a+b-c -+abc ab+c-
(A+B)*(C-D) *+AB–CD AB+CD-*
A/(B+C) /A+BC ABC+*/
X+Y/Z*A +X*/YZA XYZ/A*+
A*B^C+D +*A^BCD ABC^*D+
Dr. R. Jothi, VIT Chennai
Dr. R. Jothi, VIT Chennai
Dr. R. Jothi, VIT Chennai
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix using
stack : a + b * c
Next character Postfix Stack
Read ‘a’ a a
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a + b * c
Next character Postfix Stack
a a
Read ‘+’
+ a +
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a + b * c
Next character Postfix Stack
a a
Read ‘b’
+ a +
b ab +
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a + b * c
Next character Postfix Stack
a a
Read ‘*’
+ a +
b ab +
* ab +*
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a + b * c
Next character Postfix Stack
a a
Read ‘c’
+ a +
b ab +
* ab +*
c abc +*
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a + b * c
Next character Postfix Stack
a a
• End of i/p
string + a +
• Stack not b ab +
empty
* ab +*
c abc +*
Pop until stack
is empty abc* +
Pop *
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a + b * c
Next character Postfix Stack
a a
+ a +
b ab +
* ab +*
c abc +*
Pop +
abc* +
abc*+
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a + b * c
Next character Postfix Stack
a a
+ a +
b ab +
* ab +*
c abc +*
stack is empty
abc* +
abc*+
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a + b * c
Next character Postfix Stack
a a
Infix : a+b*c
Postfix : abc*+ + a +
b ab +
* ab +*
c abc +*
abc* +
abc*+
Dr. R. Jothi, VIT Chennai
Transforming Infix to Postfix : a - b + c
Next character Postfix Stack
a a
Infix : a-b+c
Postfix : ab-c+ - a -
b ab -
+ ab-
ab- +
c ab-c +
ab-c+
Dr. R. Jothi, VIT Chennai
Infix to Postfix using Stack (1)
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top,
push the incoming operator onto the stack.
3. If the incoming symbol is a left parenthesis, push it on the
stack.
4. If the incoming symbol is a right parenthesis, pop the stack
and print the operators until you see a left parenthesis.
Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top
of the stack, push it on the stack.
Infix to Postfix using Stack (2)
6. If the incoming symbol has equal precedence with the top
of the stack, use association. If the association is left to
right, pop and print the top of the stack and then push the
incoming operator. If the association is right to left, push
the incoming operator.
7. If the incoming symbol has lower precedence than the
symbol on the top of the stack, pop the stack and print the
top operator. Then test the incoming operator against the
new top of stack.
8. At the end of the expression, pop and print all operators on
the stack. (No parentheses should remain.)
Next character Postfix Stack
One A A
* A *
more ( A *(
example B AB *(
+ AB *(+
C ABC *(+
Infix : A * (B +C - D)
- ABC+ *(
Postfix : A B C +D - *
ABC+ *(-
D ABC+D *(-
) ABC+D- *(
ABC+D- *
ABC+D-*
Next character Postfix Stack
Exercise
Infix : A * (B + C * D) + E
Postfix : ?
Next character Postfix Stack
Exercise : fill this table to
demonstrate the steps in
converting given infix to
postfix using stack
Infix : A * (B + C * D) + E
Postfix : A*(B+(C*D) )+E
A*( B+(CD*) )+E
(A*(BCD*+))+E
(ABCD*+* )+E
ABCD*+*E+
Evaluating Postfix Expression
The stack during the evaluation of the postfix expression a b /
when a is 2 and b is 4
Dr. R. Jothi, VIT Chennai
Evaluating Postfix Expression
The stack during the evaluation of the postfix
expression a b + c / when a is 2, b is 4 and c is 3
Dr. R. Jothi, VIT Chennai
Dr. R. Jothi, VIT Chennai
Factorial using recursion
n! = n* (n-1)! int fact( int n)
{
if (n==1) return 1;
return (n*fact(n-1);
}
Dr. R. Jothi, VIT Chennai
Recursive Function calls using Stack
Dr. R. Jothi, VIT Chennai