Queues,Stacks and Topological sort - PowerPoint PPT Presentation

1 / 44
About This Presentation
Title:

Queues,Stacks and Topological sort

Description:

Queues,Stacks and Topological sort STACK QUEUES Definitions Stack First In Last Out Queue First In First Out Stacks All access is restricted to the most recently ... – PowerPoint PPT presentation

Number of Views:131
Avg rating:3.0/5.0
Slides: 45
Provided by: EricC156
Category:

less

Transcript and Presenter's Notes

Title: Queues,Stacks and Topological sort


1
Lecture 22
  • Queues,Stacks and Topological sort

2
STACK QUEUES
3
Definitions
  • Stack
  • First In Last Out
  • Queue
  • First In First Out

4
Stacks
  • All access is restricted to the most recently
    inserted elements
  • Basic operations are push, pop, top.

push
pop, top
Stack
5
Non-Computer Examples
  • Stack of papers
  • Stack of bills
  • Stack of plates
  • Expect O ( 1 ) time per stack operation. (In
    other words, constant time per operation, no
    matter how many items are actually in the stack).

6
Application
  • Stack can be used to check a program for balanced
    symbols (such as , (), ).
  • Example () is legal, () is not (so simply
    counting symbols does not work).
  • When a closing symbol is seen, it matches the
    most recently seen unclosed opening symbol.
    Therefore, a stack will be appropriate.

7
Balanced Symbol Algorithm
  • Make an empty stack.
  • Repeatedly read tokens if the token is
  • an opening symbol, push it onto the stack
  • a closing symbol
  • and the stack is empty, then report an error
  • otherwise pop the stack and verify that the
    popped symbol is a match (if not report an error)
  • At the end of the file, if the stack is not
    empty, report an error.

8
Example
  • Input ()
  • Push
  • Push ( stack has (
  • Pop popped item is ( which matches ). Stack now
    has .
  • Pop popped item is which matches .
  • End of file stack is empty, so all is good.

9
Performance
  • Running time is O( N ), where N is amount of data
    (that is, number of tokens).
  • Algorithm is online it processes the input
    sequentially, never needing to backtrack.

10
Procedure Stack
  • Matching symbols is similar to procedure call and
    procedure return, because when a procedure
    returns, it returns to the most recently active
    procedure. Procedure stack can be used to keep
    track of this.
  • Abstract idea when procedure call is made, save
    current state on a stack. On return, restore the
    state by popping the stack.

11
Activation Records
  • Actual implementation is slightly different (note
    that text describes the abstract implementation).
  • The top of stack can store the current procedure
    environment.
  • When procedure is called, the new enviromment is
    pushed onto stack.
  • On return, old enviroment is restored by pop

12
Other Applications
  • Recursion removal can be done with stacks
  • Operator precedence parsing (future lecture)
  • Reversing things is easily done with stacks

13
Queues
  • All access is restricted to the least recently
    inserted elements
  • Basic operations are enqueue, dequeue, getFront.

dequeue getFront
Queue
enqueue
14
Examples
  • Line for Panther tickets
  • Line printer queue
  • Queue is a British word for line.
  • Expect O ( 1 ) time per queue operation because
    it is similar to stack.
  • The word "queueing" and its derivatives are the
    only English words with five consecutive vowels.

15
Applications
  • Queues are useful for storing pending work.
  • We will see several examples later in the course
  • Shortest paths problem (minimize the number of
    connecting flights between two arbitrary
    airports)
  • Topological ordering given a sequence of events,
    and pairs (a,b) indicating that event a MUST
    occur prior to b, provide a schedule.

16
Array Implementations
  • Stack can be implemented with an array and an
    integer top that stores the array index of the
    top of the stack.
  • Empty stack has top equal to -1.
  • To push, increment the top counter, and write in
    the array position.
  • To pop, decrement the top counter.

17
Stages

18
Array Doubling
  • If stack is full (because array size has been
    reached), we can extend the array, using array
    doubling.
  • We allocate a new, double-sized array and copy
    contents over
  • Object OldArray Array
  • Array new Object OldArray.length 2
  • for( int j 0 j lt OldArray.length j )
  • Array j OldArray j

19
Running Time
  • Without array doubling, all operations are
    constant time, and do not depend on number of
    items in the stack.
  • With array, doubling, a push could occasionally
    be O( N ). However, it is essentially O( 1 )
    because each array doubling that costs N
    assignments is preceded by N/2 non-doubling
    pushes.

20
Queues Simple Idea
  • Store items in an array with front item at index
    zero and back item at index Back.
  • Enqueue is easy increment Back.
  • Dequeue is inefficient all elements have to be
    shifted.
  • Result Dequeue will be O( N ).

21
Better Idea
  • Keep a Front index.
  • To Dequeue, increment Front.

22
Circular Implementation
  • Previous implementation is O( 1 ) per operation.
  • However, after Array.length enqueues, we are
    full, even if queue is logically nearly empty.
  • Solution use wraparound to reuse the cells at
    the start of the array. To increment, add one,
    but if that goes past end, reset to zero.

23
Circular Example
  • Both Front and Back wraparound as needed.

b
c
d
e
f
Front
Back
b
c
d
e
f
g
Front
Back
24
(No Transcript)
25
Java Implementation
  • Mostly straightforward maintain
  • Front
  • Rear
  • Current number of items in queue
  • Only tricky part is array doubling because
    contiguity of wraparound must be maintained.

26
Next Time
  • Alternative implementations that use linked lists
    and linked lists in general
  • Answers the big Java question
  • If there are no pointers, how do you implement
    linked lists?

27
Application of Graph
  • Topological sorting

In a list of vertices in topological order,
vertex x precedes vertex y if there is a
directed edge from x to y in the graph. The
vertices in a given graph may have several
topological orders.
28
Real life example
  • For example, in your real life, course A is a
    prerequisite to course B, which is a prerequisite
    to both courses C and E. In what order should
    you take all seven courses so that you will
    satisfy all
  • prerequisite?

29
How to do topological sorting
First, you could find a vertex that has no
successor. You remove from the graph the vertex
and all edges that lead to it, and add it to the
beginning of a list of vertices. You add each
subsequent vertex that has no successor to the
beginning of the list. When the graph is empty,
the list of vertices will be in topological order.
30
Topological Sorting
  • Project is placed in to a task digraph
  • Each vertex represents a task
  • A directed edge (i,j), means that task i must be
    done before task j

31
  • Precedence relation is transitive
  • The edges (1,4) and (4,6) together imply that
    task 1 must be done before task 6
  • Any sequence that follows these properties is
    topological

32
Topological Order
  • Begin with a vertex that has nothing pointing at
    it
  • From the remaining vertices, select a vertex w
    that has no incoming edge (v,w) with the property
    that v hasnt already been placed into the
    sequence

33
Example of Task Digraph
1
3
4
6
2
5
34
Possible Topological Orders
  • 123456
  • 132456
  • 215346
  • 251346
  • These are all found using the Greedy Algorithm

35
How to do topological sorting
First, you could find a vertex that has no
successor. You remove from the graph the vertex
and all edges that lead to it, and add it to the
beginning of a list of vertices. You add each
subsequent vertex that has no successor to the
beginning of the list. When the graph is empty,
the list of vertices will be in topological order.
36
Graph
List
A
B
C
D
E
F
Remove F from Graph add it to List
G
A
B
C
F
D
E
Remove C from Graph add it to List
G
37
A
B
D
E
CF
Remove E from Graph add it to List
G
A
B
EFC
D
Remove B from Graph add it to List
G
38
A
BECF
D
Remove D from Graph add it to List
G
A
BDECF
Remove G from Graph add it to List
G
39
A
Remove A from Graph add it to List
AGDBECF
40
TOPOLOGICAL SORTING
  • We will use topological sorting to solve the
    shortest path problem for acyclic graphs.
  • DEFINITION
  • A topological sort orders vertices in a directed
    acyclic graph in such a way that if there is a
    path from u to v then v appears after u in the
    ordering.
  • Topological sorting only applies for acyclic
    graph.

41
  • HOW TO DO TOPOLOGICAL SORTING
  • The indegree of a vertex is the number of
    incoming edges.
  • The whole idea of topological sorting is to find
    the vertex with indegree 0 and logically remove
    it along with its edges from the graph. Each time
    we remove a vertex v from the graph, we lower the
    indegrees of all vertices adjacent to v.
  • If there are several vertices of indegree 0, we
    can choose any of them.
  • Continue removing indegree-0 vertices until there
    is no vertex left. All the removed vertices
    constitute a topological sort order.

42
(a)
0
(b)
43
(c)
(d)
44
(f)
(e)
(h)
(g)
Write a Comment
User Comments (0)
About PowerShow.com