0% found this document useful (0 votes)
44 views

Module 2-ND

The document discusses stacks and provides details about: - Stacks are linear data structures that only allow insertion and removal of elements from one end, called the top. - Common stack operations are PUSH to add an element and POP to remove the top element. - Stacks can be implemented using arrays, with a pointer tracking the top index. - Stacks have applications in expression evaluation, recursion, reversing data structures, and more.

Uploaded by

Neetha Das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Module 2-ND

The document discusses stacks and provides details about: - Stacks are linear data structures that only allow insertion and removal of elements from one end, called the top. - Common stack operations are PUSH to add an element and POP to remove the top element. - Stacks can be implemented using arrays, with a pointer tracking the top index. - Stacks have applications in expression evaluation, recursion, reversing data structures, and more.

Uploaded by

Neetha Das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 148

STACKS

MODULE 2
INTRODUCTION
The linear lists and linear arrays allows one to insert
and delete elements at any place in the list- at the
beginning, at the end or in the middle
There are certain frequent situations when one wants
to restricts insertions and deletions so that they can
take place only at the beginning or the end of the list,
not in the middle
They are STACKS and QUEUES
What is a stack?
 It is an ordered group of homogeneous items of elements.
 Elements are added to and removed from the top of the
stack (the most recently added items are at the top of the
stack).
 The last element to be added is the first to be removed
(LIFO: Last In, First Out).
STACKS
Stack is a linear list in which addition and deletion of
elements are restricted to one end called the top.
A linear list is a list in which each element has unique
successor.
A linear list may be a restricted list or a general list.
Stack is also called as
o LIFO Data structure
o Push down list
Stack Operations
PUSH – Used to insert an element into Stack.
POP – Used to delete an element from Stack.
Underflow is a condition occurs if we try to POP item
from the empty STACK
Overflow is a condition occurs if we try to PUSH an
ITEM to the STACK which is already full
Array representation of Stack
 Array can be used as home to the stack
 Data structure
#define MAX _STK 25
typedef struct {
int top;
char item[MAX_STK];
}STACK;
STACK s;
s.top= -1;

A B C D

top
Stack after – PUSH( ‘A’), PUSH( ‘B’), PUSH( ‘C’),
PUSH( ‘D’)
Algorithm to Push the element
PUSH(STACK, TOP, MAXSTK, ITEM)
This procedure pushes an ITEM onto a stack
1.[ Stack already filled? ]
If TOP = MAXSTK, then: print: OVERFLOW, and
return
2. Set TOP := TOP + 1 [ Increases TOP BY 1]
3. Set STACK[ TOP ] := ITEM [ Inserts ITEM in new
TOP position ]
4. Return
Algorithm to pop the element
POP(STACK, TOP, ITEM)
This procedure deletes the top element of STACK and
assigns it to the variable ITEM
1. [ Stack has an item to be removed? ]
If TOP = -1, then: Print : UNDERFLOW, and Return
2. Set ITEM := STACK[ TOP ]. [ Assigns TOP element to
ITEM ]
3. Set TOP := TOP – 1. [ Decreases TOP by 1 ]
4. Return
Stack representation using arrays in C
#define MAXSTK 10
typedef struct {
int item[MAXSTK];
int top;
}STACK;

STACK s;
s.top = -1;
Stacks using dynamic arrays
#define MAX 25
typedef struct {
int key;
/*other fields*/
}Element;
Element * stack;
int top= -1; top =0
capacity = 1; 10 (1000-1004)
stack = (Element *) malloc (sizeof (*stack)); 1000-1004

int IsFull( ) {
if ( top >= capacity – 1) stack capacity =1
return 1;
return 0;
}
Void Push(Element item)
{
If(IsFull( ))
Stackfull( );
Top++;
* stack=item;
return;
}
Stackfull( )
{
Stack=realloc(2*capacity*size of (*stack)); 2000-2008
Capacity*=2;
}
int Isempty( ){
If(top <0)
return 1;
return 0;
}
Element Pop( )
{
Element x;
If(!Is empty(s)
{
X=*stack;
top--;
return x;
}
}
Array doubling
void stackFull()
{
realloc(s , 2*capacity*sizeof(*s));
capacity * = 2;
}
Stack Applications
Expression Conversion d
C
Reversing Data
B
Expression Evaluation A
Recursion. Sum() s=abcd
{ sum()
{ sum()
3+4
Infix= 3+4 (operator between operands)
Postfix (REVERSE POLISH or SUFFIX )=34+
(operator is at end)
Prefix (polish)=+34 (operator is at the beginning)

D=3+6*(8-7); 1.() 2.$/^ 3. *,/ 4.+,-


Postfix=3+6*(87-)=3+6(87-)*=3687-*+
prefix= 3+6*(-87)= 3+*6-87= +3*6-87
Arithmetic Expression Representation
 INFIX
 PREFIX – POLISH
 POSTFIX – REVERSE POLISH or SUFFIX

INFIX POLISH REVERSE


POLISH
A+B*C +A*BC ABC*+
(A+B)*C *+ABC AB+C*
 Note
 The order of operators and operands in an INFIX expression does not uniquely
determine the order in which operations to be performed
 In POLISH and REVERSE POLISH notation the order in which the operations to
be preformed is completely determined by the position of the operators and the
operands in the expression
 No parenthesis required to determine the order
 Computer evaluates arithmetic expressions in INFIX notation in two steps
 1) Convert INFIX expression to POSTIX
 2) Evaluate the POSTFIX expression
Converting infix to postfix and Prefix -Examples
INFIX
1. A+B*C : A+[BC*] ABC*+ is POSTFIX
A+[*BC] +A*BC is PREFIX
2 (A+B)*C : [AB+]*C AB+C* is POSTFIX
[+AB]*C *+ABC is PREFIX
3 A$B*C-D+E/F/G+H: [AB$]*C-D+E/F/G+H
(Converting to postfix ) [AB$C*]-D+[EF/G/]+H
AB$C*D-EF/G/+H+ is
POSTFIX
(Converting to prefix) [$AB]*C-D+E/F/G+H
[*$ABC]-D+[//EFG]+H
++-*$ABCD//EFGH is PREFIX
Converting infix to postfix and Prefix -Examples
INFIX to POSTFIX Conversion
Given Infix Expression: ((A+B)*C-(D-E))$(F+G)
([AB+]*C-[DE-])$[FG+]
([AB+C*]-[DE-])$[FG+]
[AB+C*DE--]$[FG+]
AB+C*DE--FG+$ is Post expression
INFIX to PREFIX Conversion
Given Infix Expression: ((A+B)*C-(D-E))$(F+G)
([+AB]*C-[-DE])$[+FG]
([*+ABC]-[DE-])$[+FG]
[-*+ABC-DE]$[+FG]
$-*+ABC-DE+FG is Prefix expression
Evaluation of postfix expression
To evaluate postfix expression, create an empty stack
Scan from left to right to get a token
If token is operand place on the stack
If token is an operator remove two operands from the
stack
Perform the operation on that operands corresponding to
the operator
Result is placed back on the stack
Continue the procedure until we reach end of the
expression
Remove the answer from the stack.
Algorithm to evaluate POSTFIX expression
 EVALUATE (P)
This algorithm finds the VALUE of an arithmetic expression P written in
postfix notation
1. Append a right parenthesis “)”/# at the end of P.[this acts as a sentinel]
2. Scan P from left to right and repeat Steps 3 and 4 for each element of P
until the sentinel “)” is encountered
3. If an operand is encountered, place it on to STACK
4. If an operator is encountered, then,
(a) Remove the two top elements of STACK, where A is the top element and B is
the next-to-top element
(b) Evaluate B operator A
(c) Place the result of (b) back on stack
[End of If structure]
[End of Step 2 loop]
5. Set VALUE equal to the top element on STACK
6. Exit
Evaluating Given Postfix Expression :
Example: 6 2/ 3– 42*+
Token Stack top
[0] [1] [2]
Initially -1
6 6 0
2 6 2 1
/ 3 0
3 3 3 1
- 0 0
4 0 4 1
2 0 4 2 2
* 0 8 1
+ 8 0
eos -1 Answer=8
Postfix Evaluation
Postfix expression
62/3–42*+
stack

Postfix Expression
62 / 3 – 4 2 * +

Token
Operand,
6 PUSH onto
stack
stack

Postfix Expression
2/3–42*+

6
stack

Postfix Expression
/3–42*+

Token
Operand,
2 PUSH onto
stack

6
stack

Postfix Expression
/3–42*+

2
6
stack

Postfix Expression
3–42*+

Token
Operator, POP
/ 2 top elements
from the stack
2
and store it in
6 opnd2 and
opnd1
stack

Postfix Expression
3–42*+

opnd1 opnd2
6 2
stack

Postfix Expression
3–42*+
Evaluate
opnd1 opnd2
opnd1
6 2 operator
opnd2
stack

Postfix Expression
3–42*+

opnd1 opnd2 Res


6 / 2 3

PUSH Res onto stack


stack

Postfix Expression
3–42*+

3
stack

Postfix Expression
–42*+

Token
Operand,
3 PUSH onto
stack

3
stack

Postfix Expression
–42*+

3
3
stack

Postfix Expression
42*+

Token
Operator, POP
- 2 top elements
from the stack
3
and store it in
3 opnd2 and
opnd1
stack

Postfix Expression
42*+
Evaluate
opnd1 opnd2
opnd1
3 3 operator
opnd2
stack

Postfix Expression
42*+

opnd1 opnd2 Res


3 - 3 0

PUSH Res onto stack


stack

Postfix Expression
42*+

0
stack

Postfix Expression
2*+

Token
Operand,
4 PUSH onto
stack

0
stack

Postfix Expression
2*+

4
0
stack

Postfix Expression
*+

Token
Operand,
2 PUSH onto
stack
4
0
stack

Postfix Expression
*+

2
4
0
stack

Postfix Expression
+

Token
Operator, POP
2 * 2 top elements
from the stack
4
and store it in
0 opnd2 and
opnd1
stack

Postfix Expression
+
Evaluate
opnd1 opnd2
opnd1
4 2 operator
opnd2

0
stack

Postfix Expression
+

opnd1 opnd2 Res


4 * 2 8

PUSH Res onto stack


stack

Postfix Expression
+

8
0
stack

Postfix Expression

Token
Operator, POP
+ 2 top elements
from the stack
8
and store it in
0 opnd2 and
opnd1
stack

Postfix Expression

Evaluate
opnd1 opnd2
opnd1
0 8 operator
opnd2
stack

Postfix Expression

opnd1 opnd2 Res


0 + 8 8

PUSH Res onto stack


stack

Postfix Expression

8
Infix to postfix conversion algorithm
 Reverse polish(Q, P) // Q is an arithmetic expression in INFIX notation
Algorithm converts INFIX expression Q into POSTFIX expression P
1 push “(“ onto STACK, and append “)” to the end of Q
2 scan Q left to right and repeat Steps 3 to 6 for each element of Q until the
STACK is empty
3 If an operand is encountered place it in the POSTFIX expression P
4 If an left parenthesis is encountered, push it on to the STACK
5 If an operator is encountered, call it as incoming operator, then:
a) Repeatedly pop from the STACK and place it in the P which has the same
precedence or higher precedence than the incoming operator
b) b) Place the incoming operator to the STACK
[End of IF]
6 If a right parentheses is encountered
a) Repeatedly pop from the STACK and place it in the P until left parenthesis
is encountered
b) Remove the left parenthesis
[ End of If ]
[ End of Step 2 loop ]
Infix to postfix conversion
infixVect
(a+b-c)*d–(e+f)

postfixVect
Infix to postfix conversion
stackVect

infixVect
a+b-c)*d–(e+f)

postfixVect

(
Infix to postfix conversion
stackVect

infixVect
+b-c)*d–(e+f)

postfixVect
a

(
Infix to postfix conversion
stackVect

infixVect
b-c)*d–(e+f)

postfixVect
a

+
(
Infix to postfix conversion
stackVect

infixVect
-c)*d–(e+f)

postfixVect
ab

+
(
Infix to postfix conversion
stackVect

infixVect
c)*d–(e+f)

postfixVect
ab+

-
(
Infix to postfix conversion
stackVect

infixVect
)*d–(e+f)

postfixVect
ab+c

-
(
Infix to postfix conversion
stackVect

infixVect
*d–(e+f)

postfixVect
ab+c-
Infix to postfix conversion
stackVect

infixVect
d–(e+f)

postfixVect
ab+c-

*
Infix to postfix conversion
stackVect

infixVect
–(e+f)

postfixVect
ab+c-d

*
Infix to postfix conversion
stackVect

infixVect
(e+f)

postfixVect
ab+c–d*

-
Infix to postfix conversion
stackVect

infixVect
e+f)

postfixVect
ab+c–d*

(
-
Infix to postfix conversion
stackVect

infixVect
+f)

postfixVect
ab+c–d*e

(
-
Infix to postfix conversion
stackVect

infixVect
f)

postfixVect

+ ab+c–d*e

(
-
Infix to postfix conversion
stackVect

infixVect
)

postfixVect

+ ab+c–d*ef

(
-
Infix to postfix conversion
stackVect

infixVect

postfixVect
ab+c–d*ef+

-
Infix to postfix conversion
stackVect

infixVect

postfixVect
ab+c–d*ef+-
Precedence OF Operators

SYMBOLS Stack Input Associativity


Precedence(ISP) Precedence(ICP)

+ - 2 1 Left

* / % 4 3 Left

^ $ 5 6 Right

operands 8 8 Left

( 0 9 Left

) 0
Infix to Postfix Conversion using Stack: Example

Infix Expression : A *(B + C) / D


Token Stack top Postfix
[0] [1] [2]
A -1 A
* * 0 A
( * ( 1 A
B * ( 1 AB
+ * ( + 2 AB
C * ( + 2 A BC
) * 0 ABC+
/ / 0 ABC+*
D / 0 ABC+*D
eos -1 ABC+*D/
Infix to Postfix Conversion using Stack: Example
Infix Expression : X^Y^Z-M+N+P/Q
Token Stack top Postfix
[0] [1] [2]
X -1 X
^ ^ 0 X
Y ^ 0 XY
^ ^ ^ 1 XY
Z ^ ^ 1 X YZ
- - 0 X YZ^^
M - 0 XYZ^^M
+ + 0 XYZ^^M-
N + 0 XYZ^^M-N
+ + 0 XYZ^^M-N+
P + 0 XYZ^^M-N+P
/ + / 1 XYZ^^M-N+P
Q + / 1 XYZ^^M-N+PQ/+
Recursion
Recursion is a process in which a procedure calls itself. In C the
function that calls itself is called as recursive function.
Two types
1. Direct recursion – if the function A calls function A itself
2. Indirect recursion – if function A calls function B, function B
calls function A ( recursive chain)
A recursive procedure must have the following 2 properties
1. There must be base criteria ( terminating condition) for which
procedure doesn’t calls itself
2. Successive recursive calls should lead towards base criteria
FACT(5)- 5*FACT(4)
 4*FACT(3)
 3*FACT(2)
 2*FACT(1)
 1*FACT(0)
 1*1
 2* 1
 3*2
 4*6
 5*24
Recursion - Examples
 Recursion is implemented by means of Stacks.
 Factorial function – f(n) = n*f(n-1) for n != 0
f(n) = 1 for n = 0
Algorithm:
FACTOIAL (FACT, N)
This procedure calculates N! and returns the value in the variable
FACT
1) If N = 0, then Set FACT := 1 and Return
2) Call FACTORIAL (FACT, N-1)
3) Set FACT := N * FACT
4) Return
GCD
 GCD – gcd(m, n) = gcd( n, m mod n) for n != 0
gcd (m,n) = m for n = 0
Algorithm:
GCD(m, n)
This procedure calculates the GCD of two numbers m, n and
Returns
the value
1. If n=0 then, Set gcd := m; Return gcd
2. Call GCD ( n, m mod n)
3. End
Move nth disk from s tp te
Move n-1 disk from s to deti
Move nth disk from te to des
Example: Towers of Hanoi puzzle

In this puzzle, the player begins with n disks of decreasing diameter


placed one on top of the other on one of three pegs of the game board.
The player must move the disks from peg to peg, using each of the three
pegs, until the entire tower is moved from the starting peg to one of the
others. The only rule governing the movement of the disks is that in each
move a disk of larger diameter must never be placed on top of one of
smaller diameter
Towers of Hanoi Puzzle
Towers of Hanoi Puzzle
Towers of Hanoi
Puzzle
Towers of Hanoi
Puzzle
Towers of Hanoi
Puzzle
Towers of Hanoi
Puzzle
Towers of Hanoi
Puzzle
Solution to Tower of Hanoi Problem
 move top n-1 disks from source peg A to peg B using peg C as Auxpeg
 Transfer the remaining disk from peg A to peg C
 move n-1 disks from peg B to peg C using peg A as Auxpeg
Algorithm:
TOWER (N, Src, Aux, Dest)
//This procedure gives a recursive solution to the Towers of Hanoi problem for N
disks
1) If N=1 then :
Write : move disk 1 from Src to Dest and Return
[ End of If structure ]
2) [ Move N-1 disks from peg Src to peg Aux ]
Call TOWER( N-1, Src, Dest, Aux)
3) Write : move disk N from Src to Dest
4) [ Move N-1 disks from peg Aux to peg Dest ]
Call TOWER( N-1, Aux,Src, Dest)
5) Return
Binary Search Example

102 Chapter 7: Recursion


Ackermann function
It is a function with 2 arguments which can be assigned
non negative integer ( 0, 1,2…..).
Ackermann function is defined as follows.
A(m, n)= n+1 if m = 0
A(m, n) = A(m-1, 1) if m != 0 and n = 0
A(m, n) = A(m-1, A(m, n-1)) if m != 0 and n != 0
OR
A(0, n)= n+1 if m = 0
A(m, 0) = A(m-1, 1) if m > 0 and n = 0
A(m, n) = A(m-1, A(m, n-1)) if m >0 and n > 0
The Ackermann function is such a function, it grows
too fast to be primitive recursive.

There is no really practical uses, it grows too fast to be


useful. You can't even explicitly represent the numbers
beyond a(4,3) in a reasonable space.
Example
A(1,3) = A(0, A(1,2))
A(1,2) = A(0,A(1,1))
A(1,1) = A(0,A(1,0))
A(1, 0 ) = A(0,1)
A(0,1) = 1+1 = 2
A(1,0) = 2
A (1,1) = A(0,2) = 2+1 = 3
A(1,2) = A(0,3) = 3+1 = 4
A(1,3) = A(0,4) = 4+1 = 5
Program
#include<stdio.h>
int A(int m, int n);

main()
{
int m,n;
printf("Enter two numbers :: \n");
scanf("%d%d",&m,&n);
printf("\nOUTPUT :: %d\n",A(m,n));
}

int A(int m, int n)


{
if(m==0)
return n+1;
else if(n==0)
return A(m-1,1);
else
return A(m-1,A(m,n-1));
}
What is a queue?
It is an ordered group of homogeneous items of
elements.
Queues have two ends:
Elements are added at one end.
Elements are removed from the other end.
The element added first is also removed first
(FIFO: First In, First Out).
Conceptual View of a Queue
Adding an element

Front of queue

New element is added


to the rear of the
queue

6-110
Conceptual View of a Queue
Removing an element

New front element of queue

Element is removed
from the front of the
queue
6-111
Queue
Inserting an item into queue
void enqueue( queue , item)
{
if(rear==maxsize-1)
printf(queue is full)
else
rear=rear+1
queue[rear]=item
}

0 1 2 3
6 7 4 8
Deleting an item from queue
void dequeue()
{
if(rear==front)
printf(queue is empty)
else
{ front=front+1
return queue[front]
}
}

0 1 2 3
5
Various Queues
Normal queue (FIFO)
Circular Queue (Normal Queue)
Double-ended Queue (Deque)
Priority Queue
Multiple Queue
 rear=0 rear=rear+1%queuesize
 0+1 % 8==1

 1+1%8===2
 7+1%8==0
 8+1%8==1
Inserting and Deleting an item into queue using
count
void dqueue( queue , item)
void enqueue( queue , item) {
{ if(count==0)
if(count==maxsize) {
{ printf(queue is empty)
printf(queue is full) return
return; }
} else
else {
{ rear=(rear+1)%maxsize front=(front+1)%maxsize
queue[rear]=item; return(queue[front])
count++ count--
} }
} }

0 1 2 3
Inserting an item into queue
void enqueue( queue , item)
{

if(front==(rear+1)%maxsize)
{
printf(queue is full)
return
else
{
rear=(rear+1)%maxsize
queue[rear]=item;
}
}
0 1 2 3
Deleting an item from queue
void dqueue( queue , item)
{
if(front==rear)
{
printf(queue is empty)
return
}
else
{
front=(front+1)%maxsize
return(queue[front])
}
}

0 1 2 3
2 3 4
Display the content of queue
void display( queue , item)
{
if(front==rear)
{
printf(queue is empty)
return
else
{
while(front!=rear)
front=(front+1)%MAX;
printf("%c\t", Q[front]);
}
}
0 1 2 3
2 3
Double Ended Queue
Operations
Insert at rare end
Insert at front end
Delete from front end
Delete from rear end
Display contents of dqueue

0 1 2 3 4 5
33
Insert at front end
Case 1: when queue is empty
if(f=-1 & r=-1)
{r=r+1; q[r]=item;
return}
Case2 : When some elements are deleted
if(f!=-1)
{ q[f]=item ;
f=f-1; return}
Case 3:Some items are inserted but not deleted
4insertion at57front is not5 possible
Delete at rear end
If(f=-1 & r=-1)
dqueue is empty ; return;
else item=q[r--];
if(f==r)
f=r=-1;
Priority queues (pq)
Priority Queue is a data structure in which the elements are
assigned priority such that the order in which elements are
deleted and processed follow the following rule
Element with the higher priority is processed before
elements with lower priority
Elements with same priority are processed in the order they
are added to the queue
2 types of PQ are
Ascending PQ (APQ): In which items are inserted
arbitrarily and from which smallest item can be removed.
The basic operations are pqinsert(apq,x) and
pqmindelete(apq)
Descending PQ (DPQ): In which items are inserted
arbitrarily and from which largest item can be removed. The
basic operations are pqinsert(dpq,x) and pqmaxdelete(dpq)
1. normal insertion & special deletion
A 3
B 2
C 7
2. B A C

2.SPECIAL INSERTION AND NORMAL


DELETION
Array representation of priority queue using 2D array

FRONT REAR

3
1 2 3 4 5 6
3
1 A
1 3
2 B C X
0 0 3
1 6
4 D E F
5 G
4 4

A-1
B-2
C-2
X-2
D-4
E-4
F-4
Alogorithm
Algorithm enqueue(q[] , item)
{ if(rear=maxsize-1)
printf(“queue is full) insert 5,pos=-1, rear=0
else { pos=rear insert 2 pos=0 ,rear=1
rear=rear+1 insert 4 pos=1 ,rear=2
while(pos>=0 && q[pos]>=item
{ q[pos+1]=q[pos]
pos=pos-1;
}
q[pos+1]=item
if(front=-1)
Mazing Problem
Example
Algorithm
Two Stacks in Single Array
 S[++TOP]=ITEM;

 TOP=TOP+1
S[TOP]=ITEM
Implementation
Multiple Stacks
Example
Multiple Stacks
0 1 2 3 4 5 6 7 8 9 10 11 12
Push operation on multiple stack
Void push(int i , int item) //add item to ith stack
{ if (top[i]==boundary[i+1])
 { print(stack i is full); return }
 stack[++top[i]]=item
}
Top2= boundary[2] top3= b[3] top1=-1

0 1 2 3 4 5 6 7 8 9 10 11 12
3 4
Pop operation on multiple stack
Void pop(int i) //remove the top item from the ith
stack
{ if (top[i]==boundary[i])
 { return stack i is empty ; return; }
 return stack[top[i]--];
}

0 1 2 3 4 5 6 7 8 9 10 11 12
Display operations on multiple stack
Void Display() //remove the top item from the ith
stack
{ if (top[i]==boundary[i])
 { return stack i is empty ; return; }
 for(j=boundary[i]+1;j<=top[i];j++)
 printf(“%d”, stack[j])
}
0 1 2 3 4 5 6 7 8 9 10 11 12
4 3 3
Multiple Queues

You might also like