0% found this document useful (0 votes)
84 views54 pages

Stacks, Queues (Chapter - 6)

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

Stacks, Queues (Chapter - 6)

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

CSE-281: Data Structures and Algorithms

Stacks, Recursion and Queue


(Chapter-6)

Ref: Schaum's Outline Series, Theory and problems of Eftekhar Hossain


Data Structures
By Seymour Lipschutz Assistant Professor
Dept. of ETE, CUET
And Online Resource
Topics to be Covered
 Stacks
 Stack Implementation
 Stack Applications
 Recursion
 Recursion Applications
 Tower of Hanoi
 Queue
 Priority Queue

2
What is Stack?
 A Stack: Stores a set of elements in a
particular order

 LAST IN, FIRST OUT (LIFO) property


 The last item placed on the stack will be the
first item removed (a)

 Analogy

 A stack of coins
 A stack of dishes in a cafeteria

(b)

Figure 1: Stack of (a) Coins, (b) Cafeteria Dishes 3


What is Stack?

E top
D top D D top
C top C C C
B top B B B B
A top A A A A A

Figure 2: Diagrams of Stack

4
Stack Operations
 Stack Operations
 Create an empty stack
 Destroy a stack
 Determine whether a stack is empty
 Add a new item
 Remove the item that was added most recently
 Retrieve the item that was added most recently

5
Stack Applications
 Real life
 Pile of books
 Plate trays
 More applications related to computer
science
 Program execution stack
 Evaluating expressions

6
Array-Based Stack Implementation

 ALGORITHM OF INSERTION IN STACK:


(PUSH)
Insertion(a[], top, item, max):
If top=max then
print ‘STACK OVERFLOW’
exit
else
top=top+1
end if
a[top]=item
Exit
7
Array-Based Stack Implementation

 ALGORITHM OF DELETION IN STACK:(POP)


Deletion(a,top,item):

If top=0 then
print ‘STACK UNDERFLOW’
exit
else
item=a[top]
end if
top = top-1
Exit
8
Array-Based Stack Implementation

 ALGORITHM OF DISPLAY IN STACK

Display(top,i,a[i]):

If top=0 then
Print ‘STACK EMPTY’
exit
else
for i= top to 0
print a[i]
end for
exit
9
Algebraic Expressions

 Infix Expressions
 An operator appears between its operands
 Example: a + b Expressions

a+b
 Prefix Expressions
 An operator appears before its operands
 Example: + a b Operand Operator

 Postfix Expressions
 An operator appears after its operands
 Example: a b +

10
Algebric Expressions

 Infix Expressions (operand | operator |operand)


 a*b+c

 Prefix Expressions (operator |operand| operand)


 + *abc

 Postfix Expressions(operand|operand|operator)
 ab *c+

11
Level of Precedence

Highest

Next Highest *, /

Lowest +, -

12
Evaluation of a Postfix Expressions

 Algorithm: To find the VALUE of a postfix expression


P using STACK. 5, 6, 2, +, *, 12, 4, /, -
1. Add a right parenthesis “)” at the end of P. (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, put it on 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 × A
c) Place the result of (b) back on STACK .
5. Set VALUE equal to the top element on STACK.
6. Exit.
13
Evaluation of a Postfix Expressions (Example)
 Postfix Expression P: 5, 6, 2, +, *, 12, 4, /, -
 Infix Expression Q: 5 * ( 6 + 2 ) – 12 / 4
Symbol Scanned STACK

(1) 5 5
(2) 6 5, 6
(3) 2 5, 6, 2
6 +2 = 8
(4) + 5, 8
5 * 8 = 40
(5) * 40
(6) 12 40, 12
(7) 4 40, 12, 4
12 / 4 = 3
(8) / 40, 3
40 - 3 = 37
(9) - 37
(10) ) 14
Transforming Infix into Postfix Expressions

 Algorithm: POLISH(Q, P)
1. Push “(” onto STACK, and add “)” to the end of Q.
2. Scan Q from 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, add it to P.
4. If a left parenthesis “(” is encountered, push it onto
STACK.
5. If an operator × is encountered, then:
a) Repeatedly pop from STACK and add to P each
operator (on the top of STACK) which has the same
precedence as or higher precedence than × .
b) Add × to STACK.
15
Continued

 Algorithm: POLISH(Q, P)
6. If a right parenthesis is encountered, then:
a) Repeatedly pop from STACK and add to P each
operator (on the top of STACK) until a left
parenthesis is encountered.
b) Remove the left parenthesis. [Do not add the left
parenthesis to P.]
7. Exit

16
Example (Infix to Postfix)

 Infix Expression Q: A + ( B * C – ( D / E ↑ F ) * G ) * H

Symbol Scanned STACK Expression P

(1) A ( A
(2) + (+ A
(3) ( (+( A
(4) B (+( AB
(5) * (+(* AB
(6) C (+(* ABC
(7) - (+(- ABC *
(8) ( (+(-( ABC *
(9) D (+(-( ABC * D
(10) / (+(-(/ ABC * D 17
Example (Infix to Postfix)

 Infix Expression Q: A + ( B * C – ( D / E ↑ F ) * G ) * H

Symbol Scanned STACK Expression P


(11) E (+(-(/ ABC * DE
(12) ↑ (+(-(/↑ ABC * DE
(13) F (+(-(/↑ ABC * DEF
(14) ) (+(- ABC * DEF ↑ /
(15) * (+(-* ABC * DEF ↑ /
(16) G (+(-* ABC * DEF ↑ / G
(17) ) (+ ABC * DEF ↑ / G * -
(18) * (+* ABC * DEF ↑ / G * -
(19) H (+* ABC * DEF ↑ / G * - H
(20) ) ABC * DEF ↑ / G * - H * +
18
Recursion

 A function that calls itself is known as recursive


function and the process of calling function itself is
known as recursion.
 Every recursive function must be provided with a
way to end the recursion.
 A recursive function must have the following two
properties:
1) There must be certain arguments, called base values, for
which the function does not refer to itself.
2) Each time the function does refer to itself, the argument of
the function must closer to a base value.
 A récursive function with these following two
properties is said to be well-defined.

19
Factorial Function

20
(1)

(2)

(3)

(4)

(5)

(6)

(7)

(8)

(9)

21
Factorial Recursive Definition in C

// Computes the factorial of a nonnegative integer.


// Precondition: n must be greater than or equal to 0.
// Postcondition: Returns the factorial of n; n is
unchanged.

int fact(int n)
{
if (n == 0)
return (1);
else
return (n * fact(n-1));
}
** Self
Write the algorithm for calculating factorial of a number
using Recursion or Iteration.
22
Fibonacci Sequence

** Self
Write the algorithm for finding the Fibonacci number
using Recursion or Iteration.
23
The Towers of Hanoi

 Given
✓ three poles
✓ a set of discs on the first pole, discs of
different sizes, the smallest discs at
the top
 Goal
✓ move all the discs from the left pole to
the right one.
 Condition
✓ only one disc may be moved at a time. A B C
✓ A disc can be placed either on an
empty pole or on top of a larger disc.

24
The Towers of Hanoi

A B C

25
The Towers of Hanoi

A B C

26
The Towers of Hanoi

A B C

27
The Towers of Hanoi

A B C

28
The Towers of Hanoi

A B C

29
The Towers of Hanoi

A B C

30
The Towers of Hanoi

A B C

31
The Towers of Hanoi

A B C

32
Solution for Single Disc

Move a disc from A to C

1 1

A (Source) B (AUX) C (Dest)

33
Solution for 2 Discs

Move a disc from A to B Using C


Move a disc from A to C
Move a disc from B to C Using A

2 2
1 2 1

A (Source) B (AUX) C (Dest)

34
Solution for 3 Discs

Move 2 discs from A to B Using C


Move a disc from A to C
Move 2 disc from B to C Using A

3 3
2 3 2
1 2 1

A (Source) B (AUX) C (Dest)

35
Solution for n Discs

Move n-1 discs from A to B Using C


Move a disc from A to C
Move n-1 disc from B to C Using A

3
2
1

A (Source) B (AUX) C (Dest)

36
Solution for n Discs

Move n-1 discs from A to B Using C


Move a disc from A to C
Move n-1 disc from B to C Using A

Program

1) TOWER (n-1, A, C, B)
2) Printf (Move a disc from A to C)
3) TOWER (n-1, B, A, C)

37
Tracing for 3 Discs
Program
1) TOWER (n-1, Source, Dest, AUX)
2) Printf (Move a disc from Source to Dest) 1) A → Source
3) TOWER (n-1, AUX, Source, Dest) 2) B → AUX
3) C → Dest
1) A → Source
TOWER (3, A, B, C) 1) B → Source
2) C → AUX
3) B → Dest 2) A → AUX
3) C → Dest
A→C
TOWER (2, A, C, B) TOWER (2, B, A, C)
4

A→B B→C

TOWER 2 TOWER TOWER 6 TOWER


(1, A, B, C) (1, C, A, B) (1, B, C, A) (1, A, B, C)

A→C 1 3 C→B
5 B→A 7 A→C

38
Solution for 3 Discs

3 3
2 3 2
13 2 13

A (Source) B (AUX) C (Dest)

A→C A→B C→B A→C B→A B→C A→C

39
Solution for 4 Discs

**Self:

Recursive Solution to Tower of


Hanoi problem for n = 4

40
What is Queue?
 A Queue: is a linear list of elements in which deletions can
take place only at one end, called FRONT, and
 Insertions can take place only at other end, called the
REAR.

 FIRST IN, FIRST OUT (FIFO) property


 The first element in a queue will be the first element out of the
queue.

 Analogy

 Automobiles waiting
 People waiting in a bank
 Timesharing system in CS

41
Array Representation of Queue

AAA BBB CCC DDD ..........


1 2 3 4 5 6 7 8 N

FRONT REAR

BBB CCC DDD ..........


1 2 3 4 5 6 7 8 N

FRONT REAR

BBB CCC DDD EEE FFF ..........


1 2 3 4 5 6 7 8 N

FRONT REAR
42
Array Representation of Queue

FRONT

.......... DDD
1 2 3 4 5 6 7 8 N

REAR

43
Circular Queue

Initially Empty
1 2 3 4 5

Insert (A, B, C ) A B C
1 2 3 4 5

FRONT REAR

Delete ( A ) B C
1 2 3 4 5

FRONT REAR

Insert ( D, E ) B C D E
1 2 3 4 5

FRONT REAR 44
Circular Queue

Delete ( B, C ) D E
1 2 3 4 5

FRONT REAR

Insert ( F ) F D E
1 2 3 4 5

REAR FRONT

Delete ( D ) F E
1 2 3 4 5

REAR FRONT

Insert ( G, H ) F G H E
1 2 3 4 5

REAR FRONT 45
Circular Queue

Delete ( E ) F G H
1 2 3 4 5

FRONT REAR

Delete ( F ) G H
1 2 3 4 5

FRONT REAR

Insert ( K ) G H K
1 2 3 4 5

FRONT REAR

Delete ( G, H ) K
1 2 3 4 5

REAR FRONT 46
Algorithm 1 (Enqueue)

QINSERT (QUEUE, N, FRONT, REAR, ITEM)

1. If FRONT = 1 and REAR = N, or if FRONT = REAR + 1, then;


write: Overflow, and Return
2. [Find new value of REAR]
If FRONT : = NULL, then [Queue initially Empty]
Set FRONT : = 1 and REAR := 1
Else if REAR = N, then :
Set REAR : = 1
Else:
Set REAR : = REAR + 1

3. Set QUEUE [REAR] : = ITEM [This inserts new element]


4. Return

47
Algorithm 2 (Dequeue)

QDELETE (QUEUE, N, FRONT, REAR, ITEM)

1. [Queue already empty ?]


If FRONT = NULL , then; Write: UNDERFLOW, and Return
2. Set ITEM = QUEUE [FRONT]
3. [Find new value of FRONT]
If FRONT = REAR, then: [Queue has only one element to start]
Set FRONT : = NULL and REAR := NULL
Else if FRONT = N, then :
Set FRONT = 1
Else:
Set FRONT = FRONT + 1
4. Return

48
Priority Queue

 Collection of elements such that each element


assigned a priority and
 The order in which elements are deleted and processed
comes from the following rules :
1) An element of higher priority is processed before any element
of lower priority
2) Two elements with same priority are processed according to
the order in which they were added to the queue
 A prototype of a priority queue is time sharing system:
 Programs of high priority are processed first, and
Programs with same priority form a standard queue

49
One Way List Representation
 Each node in the list will contain three items of
information: an information field Info, a priority
number PRN and a link number LINK.

 A node X precedes a node Y in the list (1) when X has


higher priority than Y or (2) when both have the same
priority but X was added to the list before Y.

 This means that the order in the one way list


corresponds to the order of the priority queue.

50
One Way List Representation
AAA 1 BBB 2 CCC 2 DDD 4

START

EEE 4 FFF 4 GGG 5


INFO PRN LINK

1 BBB 2 6
2 7
3 DDD 4 4
4 EEE 4 9
5 AAA 1 1
6 CCC 2 3
7 10 One Way List Representation
8 GGG 5 0 of Queue
9 FFF 4 8
10 11
11 12
12 0
51
Adding Element in PQ

a) Traverse the one way-list until finding a node X whose


priority number exceeds N. Insert ITEM in front of node
X.
b) If no such node is found, insert ITEM as the last
element of the list.

52
Adding Elements in PQ

Add element (XXX, 2)

Add element (NNN, 4)

Add element (ZZZ, 7)


XXX 2

AAA 1 BBB 2 CCC 2 DDD 4

ZZZ 7
START

EEE 4 FFF 4 GGG 5

NNN 4
53
Thank You

54

You might also like