Chapter 6 - Stack and Queue PDF
Chapter 6 - Stack and Queue PDF
AND
ALGORITHM
https://sites.google.com/a/quest.edu.pk/dr-irfana-memon/lecture-slides
1
NO TOPIC CLO
01 A General Overview CLO1
02 Introduction to Data Structures and Algorithm CLO1
03 String Processing CLO1
04 Abstract Data Types CLO1
05 Linked list CLO2
06 Stack and Queue CLO2
07 Recursion CLO2
08 Complexity Analysis CLO2
09 Sorting and Searching techniques CLO2
10 Trees CLO2
11 Graph CLO3
12 P & NP CLO3
2
CHAPTER 6
Stacks and Queue
3
• What is a Stack?
• DEFINITION:
A stack is a homogeneous collection of
elements in which an element may be inserted or deleted
only at one end, called the top of the stack.
4
• Special terminology is used for two basic operations
associated with stacks:
a) “Push” is the term used to insert an element into a stack.
b) “Pop” is the term used to delete an element from a stack.
5
Suppose the following 6 elements are pushed, in
order, onto an empty stack:
AAA, BBB, CCC, DDD, EEE, FFF
Frequently designate the stack by writing:
STACK : AAA, BBB, CCC, DDD, EEE, FFF
1 2 3 4 5 6 7 8 9 10 N-1 N
TOP
6
To implement a stack, items are inserted and
removed at the same end (called the top)
To use an array to implement a stack, you need
both the array itself and an integer
The integer tells you either:
Which location is currently the top of the stack, or
How many elements are in the stack
7
STACK
1 2 3 4 5 6 7 8
TOP 3 MAXSTK 8
9
Basic operations that can be performed on a stack:
10
Basic operations that can be performed on a stack:
11
Basic operations that can be performed on a stack:
12
Basic operations that can be performed on a stack:
13
Push :
Push is the function used to add data items to the stack.
In order to understand how the Push function operates, we
need to look at the algorithm in more detail.
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44
top = 3
MAXSTK= 10 N=4
14
Push :
Push is the function used to add data items to the stack.
In order to understand how the Push function operates, we
need to look at the algorithm in more detail.
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44
top = 3 N=4
• ITEM=80 is to be inserted
15
Push :
Push is the function used to add data items to the stack.
In order to understand how the Push function operates, we
need to look at the algorithm in more detail.
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44
Item=80
top = 3 N=4
Top=top+1 // top=4
Stack[top]=item
0 1 2 3 4 5 6 7 8 9
• If ITEM=80 is to be inserted
STACK 17 23 97 44 80
top = 4 N=5
16
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44
top = 3 N=4
• If ITEM=80 is to be inserted
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44 80
top = 4 N=5
18
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44 80
top = 4 N=5
• If ITEM=80 is to be deleted
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44
top = 3 N=4
Highest : Exponentiation(↑)
Next highest : Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Example :
2 ↑ 3 + 5 *2 ↑ 2 – 12 / 6
20
The binary operation in equation may have different levels of
precedence :
Highest : Exponentiation(↑)
Next highest : Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Example :
2 ↑ 3 + 5 *2 ↑ 2 – 12 / 6
Evaluating the Exponentiations :
8 + 5 * 4 -12 / 6
21
The binary operation in equation may have different levels of
precedence :
Highest : Exponentiation(↑)
Next highest : Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Example :
2 ↑ 3 + 5 *2 ↑ 2 – 12 / 6
Evaluating the Exponentiations :
8 + 5 * 4 -12 / 6
Evaluating the Multiplication and division
8 + 20 -2
22
The binary operation in equation may have different levels of
precedence :
Highest : Exponentiation(↑)
Next highest : Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Example :
2 ↑ 3 + 5 *2 ↑ 2 – 12 / 6
Evaluating the Exponentiations :
8 + 5 * 4 -12 / 6
Evaluating the Multiplication and division
8 + 20 -2
Evaluating the Addition and subtraction
26
23
Infix notation
24
Polish Notation (prefix) :
25
Infix expressions into polish (prefix) notation :
(A+B)*C = [+AB]*C = *+ABC
26
Infix expressions into polish (prefix) notation :
(A+B)*C = [+AB]*C = *+ABC
A+(B*C) = A +[*BC] = +A*BC
27
Infix expressions into polish (prefix) notation :
(A+B)*C = [+AB]*C = *+ABC
A+(B*C) = A +[*BC] = +A*BC
(A+B)/(C-D) =[+AB]/[-CD] = /+AB-CD
28
Infix expressions into polish (prefix) notation :
(A+B)*C = [+AB]*C = *+ABC
A+(B*C) = A +[*BC] = +A*BC
(A+B)/(C-D) =[+AB]/[-CD] = /+AB-CD
Fundamental property of polish notation is that the order in
which the operation are to be performed is completely
determined by the positions of the operators and operands in
the expression.
29
Reverse Polish notation (postfix notation)
Reverse Polish notation provided a straightforward solution
for calculator or computer software mathematics because it
treats the instructions (operators) and the data (operands)
as "objects" and processes them in a last-in, first-out (LIFO)
basis.
This is called a "stack method". (Think of a stack of plates.
The last plate you put on the stack will be the first plate
taken off the stack.)
31
Evaluation of a postfix expression : Let P is an arithmetic
expression written in postfix notation. The following
algorithm, which uses a STACK to hold operands, evaluates P
Algorithm : This algorithm finds the VALUE of an arithmetic
expression P written in postfix notation.
32
AB+
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44 80 + A=3 B =12
N=5
top = 4
Evaluation of a postfix expression : Let P is an arithmetic
expression written in postfix notation. The following algorithm,
which uses a STACK to hold operands, evaluates P
Algorithm : This algorithm
x finds the VALUE of an arithmetic
expression P written in postfix notation.
1. Add a right parenthesis “)” at the end of P
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 goto step 2.
4. If an operator is encountered, then :
(a) Remove the two top element of STACK, where A
is the top element and B is the next – to – top element.
(b) Evaluate B x A.
(C) Place the result of (b) back on STACK.
[End of if structure]
[End of step 2 loop] 33
34
Quick sort is a divide-and-conquer method for sorting.
Divide and conquer method:
It works by partitioning an array into parts, then sorting each
part independently.
exchange
36
Example
We are given array of n integers to sort:
40 20 10 80 60 50 7 30 100
37
There are a number of ways to pick the pivot
element. In this example, we will use the first
element in the array:
40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
38
LOC = 0 40 20 10 80 60 50 7 30 100
LEFT = 0 RIGHT = 8
LOC=0 ; LEFT = 0 and RIGHT = 8
SCAN From right to left, IF INFO[RIGHT] < INFO[LEFT]
THEN INTERCHANGE
i.e., 100 < 40 (No interchange)
RIGHT:= RIGHT-1
39
LOC = 0 40 20 10 80 60 50 7 30 100
LEFT = 0 RIGHT = 8
LOC=0 ; LEFT = 0 and RIGHT = 8
SCAN From right to left, IF INFO[RIGHT] < INFO[LEFT]
THEN INTERCHANGE
i.e., 100 < 40 (No interchange)
RIGHT:= RIGH-1
LOC = 0 40 20 10 80 60 50 7 30 100
LEFT = 0 RIGHT = 7
40
LOC = 0 40 20 10 80 60 50 7 30 100
LEFT = 0 RIGHT = 7
LOC=0 ; LEFT = 0 and RIGHT = 7
LEFT = 1 RIGHT = 7
41
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 1 RIGHT = 7
42
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 1 RIGHT = 7
LOC = 7 30 20 10 80 60 50 7 40 100
LEFT = 2 RIGHT = 7
43
LOC = 7 30 20 10 80 60 50 7 40 100
LEFT = 2 RIGHT = 7
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 3 RIGHT
44 =7
LOC = 7 30 20 10 80 60 50 7 40 100
LEFT = 3 RIGHT = 7
LOC = 3 30 20 10 40 60 50 7 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 3 RIGHT = 6
45
LOC = 3 30 20 10 40 60 50 7 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 3 RIGHT = 6
LOC = 6 30 20 10 7 60 50 40 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 4 RIGHT = 6
46
LOC = 6 30 20 10 7 60 50 40 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 4 RIGHT = 6
LOC=3 ; LEFT = 3 and RIGHT = 6
LOC = 4 30 20 10 7 40 50 60 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 4 RIGHT = 5
47
LOC = 4 30 20 10 7 40 50 60 80 100
LEFT = 4 RIGHT = 5
30 20 10 7 40 50 60 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
Apply the above procedure repetitively until each sub list contains
one element
48
1. Set LEFT = BEG, RIGHT = END and LOC = LEFT
LOC = 0 40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 0 RIGHT = 8
49
1. Set LEFT = BEG, RIGHT = END and LOC = LEFT
2. (a) Repeat A[LOC] <= A[RIGHT] and LOC ≠ RIGHT
RIGHT := RIGHT -1
(b) if LOC =RIGHT then return
(c) If A[LOC] > A[RIGHT]
(i) interchange each other
(ii) LOC =RIGHT
(iii) Goto Step 3
LOC = 0 40 20 10 80 60 50 7 30 100
LEFT = 0 RIGHT = 8
50
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT
LOC = 0 40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 0 RIGHT = 7
51
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 0 RIGHT = 7
52
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 1 RIGHT = 7
53
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 2 RIGHT = 7
54
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
LEFT = 3 RIGHT = 7
55
This algorithm sorts an array A with N elements
1. [Initialize] TOP=NULL.
2. [Push boundary values of A onto stack when A has 2 or more elements]
If N>1, then TOP:=TOP+1, LOWER[1]:=1 and UPPER[1]:=N.
3. Repeat Step 4 to 7 while TOP!= NULL.
4. [Pop sub list from stack]
Set BEG:=LOWER[TOP], END:=UPPER[TOP]
TOP:=TOP-1.
5. Call QUICK(A,N,BEG,END,LOC). [Procedure 6.5]
6. [Push left sub list onto stacks when it has 2 or more elements]
If BEG<LOC-1 then:
TOP:=TOP+1, LOWER[TOP]:=BEG,
UPPER[TOP]=LOC-1
[End of If structure].
7. [Push right sub list onto stacks when it has 2 or more elements]
If LOC+1 < END then:
TOP:=TOP+1, LOWER[TOP]:= LOC+1,
UPPER[TOP]:= END
[End of If structure]
[End of Step 3 loop].
8. Exit
56
A function is said to be recursively defined, if a
function containing either a Call statement to itself
or a Call statement to a second function that may
eventually result in a Call statement back to the
original function.
A recursive function must have the following
properties:
1. There must be certain criteria, called base
criteria for which the function does not call itself.
2. Each time the function does call itself
(directly or indirectly), the argument of the function
must be closer to a base value
57
Factorial function: In general, we can express the
factorial function as follows: n! = n * (n-1)!
The factorial function is only defined for positive
integers.
if n<=1, then n! = 1
if n>1, then n! = n * (n-1)!
58
Procedure : FACTORIAL(FACT, N)
This procedure calculates N! and return the value in the variable FACT.
59
Step 1. start
Step 2 .Input the value of N
Step 3. FACTORIAL(FACT,N)
Step 4. Write FACT
Step 5. Exit
Procedure : FACTORIAL(FACT, N)
This procedure calculates N! and return the value in the variable FACT.
1. If N=0, then: Set FACT :=1, and Return
2. Set FACT = 1.
3. Repeat for K=1 to N
Set FACT : = K*FACT
4. Return.
60
Fibonacci Sequence : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…………………
61
Fibonacci Sequence : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…………………
Definition 6.2
(a) If n=0 or n=1, then Fn =n
(b) If n>1, then Fn =Fn-2 +Fn-1.
62
Fibonacci Sequence : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…………………
Definition 6.2
(a) If n=0 or n=1, then Fn =n
(b) If n>1, then Fn =Fn-2 +Fn-1.
Procedure: FIBONACCI(FIB, N)
This procedure calculates Fn and returns the value in the first
parameter FIB.
63
Fibonacci Sequence : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…………………
Definition 6.2
(a) If n=0 or n=1, then Fn =n
(b) If n>1, then Fn =Fn-2 +Fn-1.
Procedure: FIBONACCI(FIB, N)
This procedure calculates Fn and returns the value in the first
parameter FIB.
1. If N=0 or N=1, then : set FIB :=N, and return.
5. Return. 64
65
Disks of different sizes (call the number of disks "n") are placed on
the left hand post,
arranged by size with the smallest on top.
You are to transfer all the disks to the right hand post in the fewest
possible moves, without ever placing a larger disk on a smaller one.
The object is to move all the disks over to another pole. But
you cannot place a larger disk onto a smaller disk.
66
How many moves will it take to transfer n disks from the
left post to the right post?
Let's look for a pattern in the number of steps it takes to move
just one, two, or three disks. We'll number the disks starting
with disk 1 on the bottom.1 disk: 1 move
Move 1: move disk 1 to post C
67
2 disks: 3 moves
Move 1: move disk 2 to post B
Move 2: move disk 1 to post C
Move 3: move disk 2 to post C
68
3 disks: 7 moves
Move 1: move disk 3 to post C
Move 2: move disk 2 to post B
Move 3: move disk 3 to post B
Move 4: move disk 1 to post C
Move 5: move disk 3 to post A
Move 6: move disk 2 to post C
Move 7: move disk 3 to post C
69
3 disks: 3 moves
Its solution touches on two important topics :
B. Recurrence relations
Let TN be the minimum number of moves needed to solve the puzzle
with N disks. From the previous section T1 = 1, T2 = 3 and T3 = 7
A trained mathematician would also note that T0 = 0. Now let us try
to derive a general formula.
70
A. Recursive pattern
From the moves necessary to transfer one, two, and three disks, we can
find a recursive pattern - a pattern that uses information from one step
to find the next step - for moving n disks from post A to post C:
First, transfer n-1 disks from post A to post B. The number of moves
will be the same as those needed to transfer n-1 disks from post A to
post C. Call this number M moves. [As you can see above, with three
disks it takes 3 moves to transfer two disks (n-1) from post A to post C.]
Next, transfer disk 1 to post C [1 move].
Finally, transfer the remaining n-1 disks from post B to post C. [Again,
the number of moves will be the same as those needed to transfer n-1
disks from post A to post C, or M moves.]
72
A Queue is a linear list of elements in which deletions can take
place only at one end, called the front, and insertions can take
place only at the other end, called the rear. The terms “front”
and “rear” are used in describing a linear list only when it
implemented as a queue.
Queues are also called first-in first-out (FIFO) lists, since the
first element in a queue will be the first element out of the
queue. In other words, the order in which elements enter a
queue is the order in which they leave. This contrasts with
stacks, which are Last-in First-out (LIFO) lists.
73
The people waiting in line at a bank form a queue, where the
first person in line is the first person to be waited on; and so on.
An important example of a queue in computer science occurs in a
timesharing system, in which programs with the same priority
form a queue while waiting to be executed.
Queue for printing purposes
74
Create queue, Create (Q)
Identify either queue is empty
Add new item in queue
Delete item from queue
Call first item in queue
75
Queue may be represented in the computer in various ways,
usually by means of one-way lists or linear arrays.
Each of our queues will be maintained by a linear array
QUEUE and two pointer variables:
FRONT, containing the location of the front element of the
queue;
and REAR, containing the location of the rear element of the
queue.
The condition FRONT = NULL will indicate that the queue is
empty.
76
when an element is deleted from the queue, the value of FRONT is
increased by 1; this can be implemented by the assignment
FRONT := FRONT + 1
Similarly, whenever an element is added to the queue, the value of
REAR is increased by 1; this can be implemented by the assignment
REAR := REAR + 1
This means that after N insertions, the rear element of the queue will
occupy QUEUE[N] or, in other words, eventually the queue will occupy
the last part of the array. This occurs even through the queue itself may
not contain many elements.
77
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This procedure inserts an element ITEM into a queue.
78
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This procedure inserts an element ITEM into a queue.
79
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This procedure inserts an element ITEM into a queue.
80
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This procedure inserts an element ITEM into a queue.
81
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it
to the variable
82
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
1. [Queue already empty]
If FRONT = NULL, then Write: Underflow, and Return.
83
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
1. [Queue already empty]
If FRONT = NULL, then Write: Underflow, and Return.
2. Set ITEM = QUEUE[FRONT]
84
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
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
85
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
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
86
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
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
[End of if structure]
4. Return
87
The mathematical model of a Deque (usually pronounced like
"deck") is an irregular acronym (Operation) of double-ended
queue.
Double-ended queues are a kind of sequence containers.
Elements can be efficiently added and removed from any of its
ends (either the beginning or the end of the sequence).
88
Insertions and deletions can occur at either end but not in the
middle
Implementation is similar to that for queues
Deques are not heavily used
You should know what a deque is, but we won’t explore them
much further
89
• There are two variations of deque
–Input-restricted deque
An input restricted deque is a deque which allows insertion
at only one end of the list but allows deletion a both end of
the list.
–Output-restricted deque
An output restricted deque is a deque which allows
deletion at only one end of the list but allows insertin a
both end of the list
90
A priority queue is a collection of elements such that each
element has been assigned a priority, such that the order in
which the elements are deleted and processed comes from
the following rules:
91
Wish
You
Good Luck
92