Professional Documents
Culture Documents
28stacks & Queues
28stacks & Queues
P. P. Chakrabarti
27-03-03
27-03-03
n \0 i a \0
27-03-03
27-03-03
a \0 e a a n l k a n d \0
N e w Z S r i L
a \0
27-03-03
r r[0][0]
27-03-03
27-03-03
Pop
27-03-03
Postfix Evaluation
Code Meaning 0 1 2 Operand Operator End
Input format: [code, value] sequence Example: 12*4+3 is coded in postfix in the form of ab*c+ as 0 12 0 4 1 2 0 3 1 0 2 For evaluation, we define a stack of element-type (say integers/float, etc). The overall algorithm is as follows: (a) Read next input; (b) If input is end then top of stack contains result; (c) If input is operand, push value into stack; (d) If Input is operator, pop out (remove) the top two elements from the stack, perform the operation and push the resultant value into the stack;
27-03-03
12
4 12
48
3 48
51
10
27-03-03
4 2
5 4 2
20 2
22
3 22
2 3 22
6 22
28
11
27-03-03
fib (5) fib (3) fib (1) fib (0) fib (2) fib (1) fib (2) fib (0) fib (4) fib (3) fib (2) fib (1)
12
27-03-03
1 3
1 2
0 1
4
13
6
27-03-03
8
P.P.Chakrabarti, IIT Kharagpur
Tower of Hanoi
14
27-03-03
Tower of Hanoi
15
27-03-03
Tower of Hanoi
16
27-03-03
Tower of Hanoi
17
27-03-03
18
27-03-03
3,A,B,C
2,A,C,B A to B 2,C,B,A
1,B,C,A A to B 2,C,B,A
B to C A to B 2,C,B,A
A to B 2,C,B,A
27-03-03
2,C,B,A
1,C,A,B C to B 1,A,B,C
P.P.Chakrabarti, IIT Kharagpur
19
REAR
Enqueue
Dequeue
FRONT
20
27-03-03
Possible Implementations
Linear Arrays:
(static/dynamicaly allocated)
Circular Arrays:
(static/dynamicaly allocated)
front
21
27-03-03
Exercises
Implement the Queue as an array. (Read the concept of a circular queue). Write down the data definition and all the interface functions. Implement the Queue as a linked list. Implement a Priority Queue which maintains the items in an order (ascending/ descending) and has additional functions like remove_max and remove_min. Maintain a Doctors appointment list
22
27-03-03 P.P.Chakrabarti, IIT Kharagpur