You are on page 1of 38

Stack

C E – S E – D ATA S T R U C T U R E S
DR. DEEPTI REDDY
A S S O C I AT E P R O F E S S O R
D E P T. O F C O M P U T E R E N G I N E E R I N G ,
Unit2- Stack
Stack
◦ Introduction to Stacks, Operations on Stacks, Applications of stacks -
Expression conversion and evaluation (Polish notation), Balanced
parenthesis checker, Recursion,
Stack Real Examples
Stack of books- How books are arranged and accessed?
Stack ADT
Stack is a linear data structure which stores the elements in an ordered manner.
The elements in a stack are added and removed only from one end which is called
top.
The policy is LIFO, the element that was inserted last is the first one to be taken
out.
Operations-
1. Push(element)- inserts an element at top of the stack
2. Pop() – removes the topmost element
3. Peek()- returns the topmost element without removing
4. isEmpty() – checks if stack is empty
5. isFull()- checks if stack is full
Push operation
Step 1: IF TOP == MAX-1
◦ PRINT OVERFLOW
◦ Goto step 4

[END OF IF]
Step 2: SET TOP = TOP + 1
Step 3: SET STACK[TOP] = VALUE
Step 4: END
Pop operation
Step 1: IF TOP = -1
◦ PRINT UNDERFLOW
◦ Go to step 4

[END OF IF]
Step 2: SET VAL = STACK[TOP]
Step 3: SET TOP = TOP - 1
Step 4: END
Peek operation
Step 1: IF TOP = -1
◦ PRINT UNDERFLOW
◦ Go to step 4

[END OF IF]
Step 2: SET VAL = STACK[TOP]
Step 3: SET TOP = TOP - 1
Step 4: END
Reflection
Consider an array of size 5, used as stack. Initially the stack is empty and top=-1.

For following operations, show the elements in the stack and value of top variable.

1. Push (A)

2. Push (B)

3. Push (C)

4. Pop()

5. Peek()
1. What is the top most element and value of top after
6. Push(D)
step 5 ?
7. Push(E) 2. At which step do you get overflow message?
8. Push(F) 3. What is the top most element and value of top after
step 10 ?
9. Push(G)

10. Pop()
Program-Implement Stack using array
#define MAX 10
int pop(int stack[])
int stack[MAX], top=-1; {
void push(int stack[], int val); If (top==-1) //check if stack is empty
int pop(int stack[]); {
int peek(int stack[]); printf(“\n stack empty”);
return -1;
}
void push(int stack[], int val) else //else if stack
{ not empty
if( top==MAX-1) //check if stack is full {
printf(“\n Stack Overflow); val=stack[top];
else //else if stack not full top--;
{ return val;
top++ }
Stack[top]=val;
}
}
Application of stack
Reversing the data items
Conversion from infix to postfix/prefix expressions
Evaluation of postfix/prefix expression
Function call
Recursion
Algorithm to reverse a string
reverse(char charArr[])
{
int size = sizeof(charArr) / sizeof(char);
char stack[20];
int i; for(i = 0; i < size; ++i)
{
push(charArr[i]);
}
for(i = 0; i < size; ++i)
{
charArr[i] = pop();
}
}
Stack-Well form-ness of
Parenthesis
Parenthesis check using stack
{A + (B – C)}
Stack [10]
Algorithm
valid= true;
s= the empty stack;
while ( entire string is not read)
{ 1. valid= true
symb=next symbol of the string; 2. valid=false
if (symb == ‘(‘ || symb == ‘{‘|| symb == 3. push (symb)
‘[‘) 4. pop()
___________
else if (symb == ‘)‘ || symb == ‘}‘|| symb ==
‘]‘)
{
i= pop ();
if ( i is not the matching opener of
symb)
_________
} //end else
} //end while
if (stack s not empty)
________
Activity
Simulate the parenthesis checker algorithm for each of the following
strings by showing the contents of the stack at each point-
1. (A+B})
2. {[A+B] – [(C-D)]
3. (A+B) – {C+D}- [F+G]
4. ((H)*{([J+K])})
5. (((A))))
Polish Notations
Algebraic expressions can be written in 3 ways-
◦ Infix, e.g A+B
◦ Prefix , e.g +AB
◦ Postfix e.g AB+

Postfix notation was invented by Polish mathematician, Jan Lukasiewicz


in year 1924.
Though infix is easy for us to write, computers find it hard to evaluate as
lot of information is needed about operator precedence, brackets, etc.
Infix notation
Operator in placed in between two operands.
E.g. A+B
Mostly used by us to write algebraic expressions.
Infix notation
How do we solve given infix expression:
7 + (6 × 52 + 3)
How Do I Remember It All ... ? BODMAS !
B Brackets first
O Orders (i.e. Powers and Square Roots, etc.)
DM Division and Multiplication (left-to-right)
AS Addition and Subtraction (left-to-right)
Postfix
Use is to have parenthesis free expression, and operators placed in the
order of evaluation.
Postfix- operator placed after the operands.
E.g. AB+, AB+C*
Evaluate postfix expression
using stack
Postfix expression- 2 3 + 5 *
Algorithm to evaluate postfix
expression using stack
9 3 4 * 8 + 4 / –
Activity
Evaluate 4 5 + 6 * using stack
Convert infix to postfix
expression
Conversion is done based on operator precedence-
◦ 1. ^ (highest precedence)
◦ 2. *,/, %
◦ 3. +, - (lowest precedence)

The expression in parenthesis is used to override operator precedence.


Examples-
1. A+B*C -> A+ BC* -> ABC*+
2. A^B*C -> AB^*C -> AB^C*
3. (A+B)*C -> AB+*C -> AB+C*
Activity
Covert following infix expression to postfix
1. (A–B) * (C+D)
2. (A + B) / ( C + D) – ( D * E)
Algorithm to convert infix to
postfix
Example
3+4*5/6
Example
A – (B / C + (D % E * F) / G)* H )
Activity
Covert following infix to postfix:
1. A + B * C + D
2. A * B + C * D
3. (A + B) * (C + D)
4. 9 - ((3 * 4) + 8) / 4.
Solve using stack and show the steps
Stack-Well form-ness of
Parenthesis
Stacks can be used to check the validity of parentheses in any algebraic
expression.
Algebraic expression is valid if for every open bracket there is a corresponding
closing bracket.
For example, the expression (A+B} is invalid but an expression {A + (B – C)} is
valid.
Recursion
A recursive function is defined as a function that calls itself to solve a smaller
version of its task until a final call is made which does not require a call to itself.
Since a recursive function repeatedly calls itself, it makes use of the system
stack to temporarily store the return address and local variables of the calling
function.
Every recursive solution has two major cases-
◦ Base case, in which the problem is simple enough to be solved directly
without making any further calls to the same function.
◦ Recursive case, in which first the problem at hand is divided into simpler
sub-parts.
Recursion - Example
Calculating factorial- n! = n * (n–1)!
5! = 5 * 4 * 3 * 2 * 1 = 120
5! = 5 * 4!, where 4!= 4 * 3!

Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1.


Recursive case of the factorial function will call itself but with a smaller value
of n, this case can be given as
factorial(n) = n × factorial (n–1)
Recursion - Example
int Fact(int n)
{
if(n==1)
return 1;
else
return (n * Fact(n–1));
}
Fact (4)= 4 * Fact(3) = 3* Fact (2)= 2* Fact(1)
Recursion - Example
Calculating Greatest Common Divisor (GCD)
The greatest common divisor of two numbers (integers) is the largest integer that
divides both the numbers.
We can find the GCD of two numbers recursively by using the Euclid’s
algorithm that states
GCD (a, b) = b, if b divides a
◦ GCD (b, a mod b), otherwise

GCD(10,8)=GCD(8,2)=2
Activity- Fill in the blanks
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
◦ return ___;

else
◦ return (GCD(___, ___));

}
Activity
Write base case and recursive function for
1. Finding sum of n numbers, e.g. sum (4)= 1+2+3+4=10
2. Calculating Fibonacci number of the given term, e.g Fib(0)=0, Fib(1)=1,
Fib(2)= 1, Fib(3)=2, Fib(4)=3, Fib(5)= 5, Fib(6)= 8…
Tower of Hanoi
The tower of Hanoi is one of the main applications of recursion.
It says, ‘if you can solve n–1 cases, then you can easily solve the nth case’.

Start state Final state


The problem is to move all these rings from pole A to pole C while maintaining
the same order.
The rule is to move one disk at a time and that the smaller disk must always
come above the larger disk.
Tower of Hanoi
1. First shift the upper two
rings (n–1 rings) from the
source pole to the spare pole.
2. Move the nth ring to
destination pole
3. Move n-1 rings from spare
pole to destination pole.
Tower of Hanoi
Base case: if n=1
Move the ring from A to C using B as spare
Recursive case:
Move n – 1 rings from A to B using C as spare
Move the one ring left on A to C using B as spare
Move n – 1 rings from B to C using A as spare
Tower of Hanoi
void move(int n, char source, char dest,
#include <stdio.h> char spare)
int main() {
{ if (n==1)
int n; printf("\n Move from %c to %c",source,dest);
printf("\n Enter the number of else
rings:”); {
scanf("%d", &n); move(n–1,source,spare,dest);
move(n,'A', 'C', 'B'); move(1,source,dest,spare);
return 0; move(n–1,spare,dest,source);
} }
}

You might also like