You are on page 1of 31

RMIT Classification: Trusted

Queues and Stacks


RMIT Classification: Trusted

Learning Objectives
1. Understand the structure and operations of:
o Queues
o Stacks
2. Be able to implement the above data structures

2
RMIT Classification: Trusted

Queues
RMIT Classification: Trusted

The Queue ADT


• A queue is like a line of people – FIFO (First in, first out)
o New items enter at the back (rear) of the queue
o Items leave the queue from the front
• Example
o Teller at a bank or cashier in a supermarket
• Queue operations include:
o Test whether a queue is empty
o Add new entry to back of queue
o Remove entry at front of queue
o Read entry at front of queue

4
RMIT Classification: Trusted

Queue Operations

5
RMIT Classification: Trusted

Queue Examples
• q1.enqueue(1)
What do the initially empty queues
• q1.enqueue(2)
- q1 and q2 – “look like” after the • q2.enqueue(3)

following sequence of operations • q2.enqueue(4)


• q1.dequeue()
• qfront = q2.peekfront()
• q1.enqueue(qfront)
• q1.enqueue(5)
• q2.dequeue()
• q2.enqueue(6)

6
RMIT Classification: Trusted

The Priority Queue


• Operations
o Test whether priority queue empty
o Add new entry to priority queue in sorted
position based on priority value
o Remove from priority queue entry with
highest priority
o Get entry in priority queue with highest priority

• Example
o Hospital emergency room

7
RMIT Classification: Trusted

Model Bank Queue Wait Times


Arrival Time Transaction
• Determine how long customer waits to get service, the
Length
average queue length, etc. as a function of arrival
20 6
rate, serving time and number of tellers
22 4
• Objectives – determine how many tellers to employ, 23 2
measure customer experience 30 3

8
RMIT Classification: Trusted

Simulation Techniques
• A discrete-event simulation (DES) models the operation of a system as
a (discrete) sequence of events in time
o Each event occurs at a particular instant in time and marks a change of state
o Between consecutive events, no change in the system is assumed to occur; thus the
simulation time can directly jump to the occurrence time of the next event

• Fixed-increment time progression, where time is broken up into small


time slices and the system state is updated according to the set of
events/activities happening in the time slice.
• Because not every time slice has to be simulated, a next-event time
simulation can typically run much faster than a corresponding fixed-
increment time simulation.
9
RMIT Classification: Trusted

Event Driven Simulation Example


• Use of a queue to model people waiting for one teller

• Events - arrivals and departures

• Generic Algorithm

10
RMIT Classification: Trusted

Trace of the Bank Simulation

11
RMIT Classification: Trusted

Water Jug Problem


• How to get exactly 2 liters of water from a 3 liters and a 4 liters jugs

• These jugs don’t have markings

12
RMIT Classification: Trusted

Breadth First Search


• Model the amount of water in 2 jugs as <X, Y>

• Initially we have <0, 0>

• We want to achieve either <2, y> or <x, 2> (x,y >= 0)

• We can move from a state <x1, y1> to several other states <x2, y2>,
<x3, y3>, <x4, y4>, etc.

• We can search this state space to find the path from <0, 0> to one of
the goal state <2, y> and <x, 2>

• Use a queue to implement this search order


13
RMIT Classification: Trusted

BFS with a queue


• enqueue initial state to queue

while queue != empty


currState = dequeue

if currState == goal state


announce & quit

generate valid & not


duplicated states from
currState and add to queue

end while

14
RMIT Classification: Trusted

Stacks
RMIT Classification: Trusted

The Stack ADT


• A stack is like a tower of building blocks – LIFO (Last in, first out)
o New items enter the top of the stack
o Items leave the stack from the top
• Stack operations
o Test whether a stack is empty
o Push an entry to top of the stack
o Pop the top of the stack
o Read the last entry added to the stack

16
RMIT Classification: Trusted

The Stack ADT


• Stack Operations • Stack Applications:
o Operating Systems

o Path Finding

o Compilers

17
RMIT Classification: Trusted

Checking for Balanced Braces


• Balanced - abc{defg{ijk}{l{mn}}op}qr
• Unbalanced – abc {def}}{ghij{kl}}m
• Using a stack
For each char in string
if (char == ‘{‘) then stack.push(‘{‘)
if (char == ‘}’) then
if (stack.peek == ‘{ ‘) then stack.pop else fail
if stack is empty then succeed else fail

18
RMIT Classification: Trusted

Tracing the Solution


• Traces of the algorithm that checks for balanced braces

• Note that we could use a simpler solution - just use a counter that must never
go negative. However, what if we have more than one type of parentheses?
19
RMIT Classification: Trusted

Matching Parenthesis
• Extend the balanced braces solution so that the expression can contain 3 types
of delimiters (). {}, []
o Valid - abc[d(ef)gh]i{jk}

o Invalid - abc[d(ef)gh}i{j], abc(de}

• In this case, we could use the same code as before, with one small modification
For each char in string
If char = {, (, or [ then stack.push {, ( or [ respectively

If char = }, ) or ] then
if stack.peek == a {, ( or [ respectively then pop else fail

If stack is empty then succeed else fail

20
RMIT Classification: Trusted

VTN-Air Flights

Adjacency List 21
RMIT Classification: Trusted

Trace of Search Algorithm

Use of stack to determine if we can fly between two cities


22
RMIT Classification: Trusted

Infix Expressions
• Grammar that defines language of fully parenthesized infix
expression

• What are the values of the following expressions?


o 5+2+3, 5 - 2 * 2, 5 - 4 - 3, 5 - 4 + 3, 15/4/2, 2** 3**2, 8÷2*(4+4)
• Are there other/better ways of writing an arithmetic expression?
RMIT Classification: Trusted

Algebraic Expressions
• Infix - binary operator appears • No need for ( ) in prefix/postfix
between its operands - a + b o a+(b*c), + a * b c, a b c * +
• Prefix - operator appears before its o (a + b) * c, * + a b c, a b + c *
operands - + a b • Convert to prefix and postfix
• Postfix - operator appears after its o (a + b) * (c – d)
operands a b +. This is often called o 2+3+4
RPN or reverse polish notation
o (2+3) * 4
• Note that when converting, the o (2+3) * (5-4)
sequence of the operands is the
o ((2 + (6*3)) – (5+2))
same, just the operators need move
and parentheses are removed
24
RMIT Classification: Trusted

Evaluating Postfix Expressions

25
RMIT Classification: Trusted

Converting Infix to Postfix

Converting
a - (b + c * d) /e

26
RMIT Classification: Trusted

Stack Implementations

Array Based Implementation

Link Based Implementation

27
RMIT Classification: Trusted

Lists Generalizes Stacks and Queues


• List has getLength

• insert replicates push and enqueue

• remove replicates pop and dequeue

• getEntry replicates peek and peekFront

28
RMIT Classification: Trusted

Comparison of Stack and Queue


• Can be implemented using an Array or a List
• Push inserts a new item at the top of the stack,
enqueue inserts it at the back of queue
• Pop removes the most recent item from the top of the
stack, dequeue removes the first item from the front
• peek gets the most recent item from the top,
peekFront gets the first item from the front of the
queue
• isEmpty checks if any items exist in the ADT
• Differences are whether function manipulates front or
back of ADT

29
RMIT Classification: Trusted

Using Queues and Stacks


• How do we use a stack to reverse a string?
• How can a queue and a stack be used to check if a string is
palindromic?

The results of inserting the


characters a, b, c, b, d into
both a queue and a stack

30
RMIT Classification: Trusted

Copyright © 2017 RMIT University Vietnam

You might also like