Chapter 3
Chapter 3
References:
- E. Horowitz, S. Sahni and S. Anderson-Freed, Fundamentals of Data Structures (2nd Edition)
- Slides are credited from Prof. Chung, NTHU
Outline
• The Stack Abstract Data Type
• The Queue Abstract Data Type
• A Mazing Problem
• Evaluation of Expressions
C
B
A top
The Stack ADT (2)
• System stack
– Stack frame of function call
item
Top
stack
item Top
THE QUEUE ADT
The Queue ADT (1)
• A queue is an ordered list in which all insertion take
place one end, called the rear and all deletions take
place at the opposite end called the front
• First-In-First-Out (FIFO) list
• If we insert the elements A, B, C, D, E, in that order,
then A is the first element we delete from the
queue as a
rear
rear C
rear B front
rear A front
The Queue ADT (2)
The Queue ADT (3)
• Using a one dimensional array and two
variables, front and rear
• As jobs enter and leave the system, the queue gradually shift to right.
• In this case, queue_full should move the entire queue to the left so that the
first element is again at queue[0], front is at -1, and rear is correctly positioned.
– Shifting an array is very time-consuming, queue_full has a worst case
complexity of O(MAX_QUEUE_SIZE).
• The entrance is at 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
R2C4D3 1 0 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
1 0 0 1 1 0 1 1 0 1 1 1 1 1 0 1 1 █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
R1C5D5
1 1 1 0 0 0 1 1 0 1 1 0 0 0 0 0 1 █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
R1C4D2 1 0 0 1 1 1 1 1 0 0 0 1 1 1 1 0 1 █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
R1C3D2 1 0 1 0 0 1 1 1 1 1 0 1 1 1 1 0 1 █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
R2C2D1
R1C1D1
3 maze[11][15]: exit
A Mazing Problem (7)
• Review of add and delete to a stack
A Mazing Problem (8)
A Mazing Problem (9)
• Analysis:
– The worst case of computing time of path is
O(mp), where m and p are the number of rows
and columns of the maze respectively
0 0 0 0 0 1
1 1 1 1 1 0
1 0 0 0 0 1
0 1 1 1 1 1
1 0 0 0 0 1
1 1 1 1 1 0
1 0 0 0 0 1
0 1 1 1 1 1
1 0 0 0 0 0 m*p
Simple maze with a long path
EVALUATION OF EXPRESSIONS
Evaluation of Expressions (1)
• The representation and evaluation of
expressions
((rear+1==front) || ((rear==MAX_QUEUE_SIZE-1) && !front))
x = a/b - c+d*e - a*c
– If we examine expressions, we notice that they
contains
• operators: ==, +, -, ||, &&, !
• operands: rear, front, MAX_QUEUE_SIZE
• parentheses: ( )
6 2 / 3 - 4 2 * +
not an
notoperator,
an annotoperator,
operator, an operator,
an operator,
pushpop
pushtwo
into pop
thevalue,
intopush
thetwo
stack into
value,
stackthe stack 3
2
calculatecalculate
it and it and
6/2-3
6/2
6 top
push thepush
resultthe
into
result
the stack
into the stack
46