Title: Data Structures
1Data Structures
- 3. Stacks and Queues
- Chih-Hung Wang
- Fall 2009
- Textbook Ellis Horowitz, Sartaj Sahni and Dinesh
P. Mehta. Fundamentals of Data Structures in C
(Second Edition). Silicon Press, 2007.
2Template Functions
- A template may be viewed as a variable that can
be instantiated to any data type, irrespective of
whether this data type is a fundamental C type
or a user-defined type.
3Selection Sort Using Templates
4Code Fragment Illustrating Template Instantiation
5Template Function to Change the Size of 1D Array
6Container
- A container class is a class that represents a
data structure that contains or stores a number
of data objects. - Objects can usually be added to or deleted from a
container class. - Bag a class of container.
- Can use the template calss.
7Template Class Bag
Bag ltintgt a Bag ltRectanglegt r
8Implementation of Bag (1)
9Implementation of Bag (2)
10The Stack ADT
- A stack is an ordered list in which insertions
and deletions are made at one end called the top.
- A Last-In-First-Out (LIFO) list.
E D C B A
D C B A
D C B A
top
top
C B A
top
B A
top
top
A
top
pop
add
add
add
add
11Application of the Stack(1)
Railroad switching network
12Application of the Stack(2)System Stack
activation record or stack frame
fp
a1
fp
previous frame pointer
previous frame pointer
return address
return address
main
main
13Stack ADT
private T stack int top int
capacity
14Implementation of the Stack (1)
template ltclass Tgt StackltTgtStack (int
stackCapacity) Capacity (stackCapacity)
if (capacity lt 1) throw Stack capacity must be
gt0 stack new Tcapacity top -1
template ltclass Tgt Inline bool Stack
ltTgtIsEmpty() const return top -1 template
ltclass Tgt Inline T Stack ltTgtTop() const
if (IsEmpty ()) throw Stack is empty
return stacktop
15Implementation of the Stack (2)
Adding to a stack
16Implementation of the Stack (3)
Deleting from a stack
17The Queue ADT
- A queue is an ordered list in which insertions
and deletions take place at different ends. - Add at the rear delete at the front.
- It is also known as First-In-First-Out (FIFO)
list.
18Inserting and Deleting in a Queue
19Queue ADT
20Queues Represented with Front element in queue0
21Queues Represented with Front element in
queuefront
Problem when rear equals capacity-1 and front
gt0 Shift all elements to the left end of the
queue!
22Shift Elements to the Left of the Queue
(a) Before shift
(b) After shift
23Circular Queue
(c) Deletion
(b) Addition
(a) Initial
24Code for Circular Queue (1)
- if (rearcapacity -1) rear0
- else rear
- (rear1) capacity
25Code for Circular Queue (2)
Private T queue int front,
rear, capacity
template ltclass Tgt QueueltTgtQueue (int
queueCapacity) capacity(queueCapacity)
if (capacity lt1) throw Queue capacity must be
gt0 queuenew Tcapacity
frontrear0
26Code for Circular Queue (3)
template ltclass Tgt inline bool QueueltTgtIsEmpty()
return frontrear template ltclass Tgt inline
T QueueltTgtFront() if (IsEmpty()) throw
Queue is empty. No front element return
queue (front 1) capacity template
ltclass Tgt inline T QueueltTgtRear() if
(IsEmpty()) throw Queue is empty. No rear
element return queuerear
27Empty and Full
5 additions to Fig. 3.8(a)
3 deletions from Fig. 3.8(a)
We cannot distinguish between an empty and a full
queue.
28Adding to a Queue (Double Size)
29Doubling Queue Capacity (1)
Capacity-1
front1
rear
After array doubling
0
30Doubling Queue Capacity (2)
After shifting right segment
Alternative configuration
31Doubling Queue Capacity (3)
- The configuration
- Create a new array newQueue of twice the capacity
- Copy the second segment (i.e., the elements
queuefront1 through queuecapacity-1) to
positions in newQueue beginning at 0. - Copy the first segment (i.e., the elements
queue0 through queuerear) to positions in
newQueue beginning at capacity-front-1.
32Doubling Queue Capacity (4)
33Deleting from a Queue
34Subtyping and Inheritance in C
- Inheritance is used to express subtype
relationships between ADTs. - As the IS-A relationship.
- Type B IS-A Type A means B is more specialized
than A or A is more general than B. - Example
- Chair IS-A Furniture
- Lion IS-A Mammal
- Rectangle IS-A Polygon
35Bag and Stack
36Implementation of Stack Operations
37Inheritance work
- Bag b(3)
- Stack s(3)
- b.Push(1) // use BagPush
- s.Push(1) // StackPush not defined use
BagPush - b.Pop() // use BagPop and BagIsEmpty
- s.Pop() // use StackPop? call BagIsEmpty
because IsEmpty has not been redefined in Stack
38A Mazing Problem
entrance
exit
Find a path!
39Allowable Moves
NW
N
NE
W
E
SW
SE
S
40Offset Move
- Struct offsets
-
- int a, b
-
- enum directions N, NE, E, SE, S, SW, W, NW
- offsets move8
gimoveSW.a hjmoveSW.b 34 ?
3144-13
41Algorithm of Finding a Path
stack
42Stack Size A Maze with a Long Path
entrance
exit
43Analysis of Path
- Storage
- 2D array maze, mark O(mp)
- Stack O(mp)
- Time complexity
- There are at most eight iterations of the inner
while loop for each marked position. for each
direction. - Each iteration takes O(1) time.
- The outer while loop ? stack empty
- If the number of zeros in the maze is z, at most
z positions can be marked. - Since z is bounded above by mp, the computing
time is O(mp).
44Overloading ltlt
templateltclass Tgt ostream operatorltlt(ostream
os, StackltTgt s) os ltlt s.top ltlt endl
for (int i 0 i lt s.top i) os ltlt i
ltlt ltlt s.stacki ltlt endl return
os ostream operatorltlt(ostream os, Items
item) return os ltlt item.x ltlt , ltlt item.y
ltlt , ltlt item.dir
45Evaluation of Expressions
- Example
- X((A/(B-CD))(E-A)C
- Priority of operators in C
46Postfix Notation
- Infix AB/C
- Postfix ABC/
- Infix A/B-CDE-AC
- Postfix AB/C-DEAC-
- Infix (A/B)-(CD)(E-A)C
- AB/CDEA-C-
47Postfix Evaluation
operation postfix
48Algorithm of Postfix Evaluation
void Eval(Expression e) // Evaluate the postfix
expression e?It is assumed that the last token (a
token // is either an operator, operand, or
) in e is . A function NextToken is //
used to get the next token from e. The function
uses the stack stack StackltTokengtstack //
initialize stack for (Token x NextToken(e)
x! xNextToken(e)) if (x is an
operand) stak.Push(x) // add to stack else
// operator remove the correct number
of operands for operator x from stack
perform the operation x and store the result (if
any) onto the stack
49Infix to Postfix (1)
- Example
- A/B-CDE-AC
- Procedure
- Fully parenthesize the expression
- Move all operators so that they replace their
corresponding right parentheses - Delete all parentheses
- Result
- ((((A/B)-C)(DE))-(AC))
- AB/C-DEAC-
50Infix to Postfix (2)--Algorithm
void Postfix(Expression e)
StackltTokengtstack // initialize stack
stack.Push() for (Token x NextToken(e)
x ! x NextToken(e)) if (x is an
operand) cout ltlt x else if (x ))
// unstack until (
for (stack.Top( ) ! ( stack.Pop( ))
cout ltlt stack.Top( )
stack.Pop( ) // unstack (
else // x is an operator for (
isp(stack.Top( )) lt icp(x) stack.Pop( ))
cout ltlt stack.Top( )
stack.Push(x) // end of
expression empty the stack for (
!stack.IsEmpty( ) cout ltlt stack.Top( ),
stack.Pop( )) cout ltlt endl
Time complexity T(n) n is the number of
tokens In the expression
51Another Example
stack