Applications of Stack

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Recursion

The process in which a function calls itself directly or indirectly is called


recursion.
In recursion, a function either calls itself directly or calls another function
which called the previous function.

Need of Recursion:
Recursion is an amazing technique with the help of which we can reduce the
length of our code and make it easier to read and write.

Properties of Recursion:
• Performing the same operations multiple times with different inputs.
• In every step, we try smaller inputs to make the problem smaller.
• Base condition is needed to stop the recursion otherwise infinite loop will
occur

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Tail Recursion
1. In void function, a recursive function is called tail recursion if it is the
last statement to be executed inside the function.
void display1(int n)
{
if(n ==0)
return;
printf(“%d”,n);
display1(n-1); /* Tail recursive call
}

void display2(int n)
{
if(n ==0)
return;
display2(n-1); /* Not a Tail recursive call
printf(“%d”,n);
}

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


2. In a non void function, if the recursive call appears in the return statement
and that call is not part of an expression then the call is tail recursive.

int GCD(int a, int b)


{
if(b ==0)
return a;
return GCD(b, a%b); /* Tail recursive call
}

int fact(int n)
{
if(n ==0)
return 1;
return (n*fact(n-1)); /* Not a Tail recursive call
}

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Direct and Indirect Recursion
Direct Recursion: If a function f1() is called
inside its own function body, then that
recursion is direct recursion.
int fib(int n)
{
if(n ==0 || n==1)
return 1;
return (fib(n-1)+fib(n-2));
} f1()
{

Indirect Recursion: If a function f1() calls f2() f2();
and the function f2() in turn calls f1(), then this is …
}
indirect recursion.
f2()
{

f1();

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India }
Tower of Hanoi

Tower of Hanoi is a mathematical puzzle where we have three rods (A, B,


and C) and N disks. Initially, all the disks are stacked in decreasing value
of diameter i.e., the smallest disk is placed on the top and they are on rod
A. The objective of the puzzle is to move the entire stack to another rod
(here considered C), obeying the following simple rules:

 Only one disk can be moved at a time.


 Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is
the uppermost disk on a stack.
 No disk may be placed on top of a smaller disk.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Move disk 1 from A to C (A->C)
Move disk 2 from A to B (A->B)
Move disk 1 from C to B (C->B)
Move disk 3 from A to C (A->C)
Move disk 1 from B to A (B->A)
Move disk 2 from B to C (B->C)
Move disk 1 from A to C (A->C)

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


General Solution:
Step 1 − Move upper n-1 disks from source (A) to aux (B) using destination
(C) as a temporary pillar

Step 2 − Move nth disk from source(A) to destination (C)

Step 3 − Move n-1 disks from aux(B) to destination (C) using source (A) as
the temporary pillar.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


void tofh(int ndisk, char source, char temp, char dest)
{
if(ndisk == 1)
{
printf(“Move Disk %d from %c%c\n”, ndisk, source, dest);
return;
}
tofh(ndisk-1, source,dest,temp);
printf(“Move Disk %d from %c%c\n”, ndisk, source, dest);
tofh(ndisk-1, temp,source,dest);
}

Recursive Equation : T(n) = 2T(n-1) + 1

T(n)= O( 2n - 1), or you can say O(2n) which is exponential.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Notation
The way to write arithmetic expression is known as a notation.
An arithmetic expression can be written in three different but
equivalent notations
1. Infix Notation
2. Prefix (Polish) Notation
3. Postfix (Reverse-Polish) Notation

Infix Notation: The conventional method of representing an arithmetic


expression is known as infix because the operator is placed in between the
operands. eg. A+B
Prefix Notation: If the operator is placed before the operands then this
notation is called Prefix of polish notations. eg. +AB
Postfix Notation: If the operator is placed after the operands then this
notation is called Prefix of polish notations. Eg. AB+

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Evaluation of a Postfix Expression

1. Add a ) at the end of the postfix expression


2. Scan every character of the postfix expression and repeat Steps 3 and 4
until ) is encountered
3. If an operand is encountered, out it on the STACK.
4. If an operator O is encountered, then
1. POP the two top elements of STACK as A(topmost element) and
B(next-to-top element).
2. Evaluate B O A.
3. Push the result of evaluation on the STACK.
5. SET RESULT equal to the topmost element of the STACK.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Given postfix expression: 456*+

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Consider the following postfix notation 8 2 3 * 8 + 2 / –. The equivalent infix
expression is 8 – ((2 * 3) + 8) / 2

The final number in the stack, 1, is the value of the postfix expression.
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Evaluation of a Prefix Expression
Consider the following prefix notation: /+33-+47*+123.
First reverse the prefix expression is 321+*74+-33+/

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Infix expression to a Postfix expression
1. Scan the infix expression from left to right.
2. If the scanned character is an operand,
put it in the postfix expression.
3. If the scanned character is a ‘(‘,
push it to the stack.
4. If the scanned character is a ‘)’,
pop the stack and output it until a ‘(‘ is encountered, and discard both the
parenthesis.
5. If the scanned character is an operator,
(a) pop the operators that have precedence greater than or equal to the precedence
of the symbol operator, and add these popped operators to the array postfix.
(b) Push the scanned symbol operator on the stack. (Assume that left parenthesis
has the least precedence).
6. After all the symbols of array infix have been scanned, pop all the operators remaining
on the stack and add them to the array postfix.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


S. No. Operator Description Associativity
1 () Parentheses Left to right
2 [] Brackets Left to right
3 . Object Left to right
4 -> Pointer Left to right
5 ++ — Postfix increment and decrement Left to right
6 ++ — Prefix increment and decrement Right to left
7 – Unary plus/minus Right to left
8 !~ Logical negation and bitwise complement Right to left
9 (type) Cast Right to left
10 * Dereference operator Right to left
11 & Address of operator Right to left
12 sizeof Unary operator, returns size in bytes. Right to left
13 */% Multiplication/ division/ modulus Left to right
14 +,– Addition/ Subtraction Left to right
15 << >> Bitwise left shift/ Bitwise right shift Left to right
16 < <= Relation less than, less than or equal to Left to right
17 > >= Relational greater than, greater than or equal to Left to right
18 == != Is equal to, Not equal to Left to right
19 & Bitwise AND Left to right
20 ^ Bitwise exclusive OR Left to right
21 | Bitwise inclusive OR Left to right
22 && Logical AND Left to right
23 || Logical OR Left to right
24 ?: Ternary operator Left to right
25 = Assignment operator Right to left
26 += -= Addition/Subtraction assignment Right to left
27 *= /= Multiplication/division assignment Right to left
28 %= &= Modulus/Bitwise AND assignment Right to left
29 ^= |= Bitwise exclusive/ Bitwise inclusive OR Right to left
30 <<= >>= Bitwise left shift/ Bitwise right shift assignment Right to left
31 , Comma operator Left to right
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Consider the following expression:
A+(B*C/D-E^F^I+G)/H
Its postfix will be:
Input symbol Stack Postfix

A Empty A
+ + A
( +( A
B +( AB
* +(* AB
C +(* ABC
/ +(/ ABC*
D +(/ ABC*D
– +(- ABC*D/
E +(- ABC*D/E
^ +(-^ ABC*D/E
F +(-^ ABC*D/EF
^ +(-^ ABC*D/EF^
I +(-^ ABC*D/EF^I
+ +(+ ABC*D/EF^I^-
G +(+ ABC*D/EF^I^-G
) + ABC*D/EF^I^-G+
/ +/ ABC*D/EF^I^-G+
H +/ ABC*D/EF^I^-G+H
NULL Empty ABC*D/EF^I^-G+H/+

Thus, the outcome of the above expression in postfix is: ABC*D/EF^I^-G+H/+


Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Infix expression to Prefix expression

To convert an infix expression to a prefix expression, we can use the stack data
structure. The idea is as follows:

Step 1: Reverse the infix expression. Note while reversing each ‘(‘ will become
‘)’ and each ‘)’ becomes ‘(‘.

Step 2: Convert the reversed infix expression to “nearly” postfix expression.


While converting to postfix expression, instead of using pop operation to pop
operators with greater than or equal precedence, here we will only pop the
operators from stack that have greater precedence.

Step 3: Reverse the postfix expression.

The stack is used to convert infix expression to postfix form.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India

You might also like