stack and queue
DESCRIPTION
Stack and QueueTRANSCRIPT
![Page 1: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/1.jpg)
1
Implementing and Using Stacks
many slides taken from Mike Scott, UT Austin
![Page 2: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/2.jpg)
2
Stacks Stacks are a straight forward and simple data
structure Access is allowed only at one point of the
structure, normally termed the top of the stack, so the operations are limited:– push (add item to stack)– pop (remove top item from stack)– top (get top item without removing it)– clear– isEmpty– size
![Page 3: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/3.jpg)
3
Stack OperationsAssume a simple stack for integers.
Stack s = new Stack();
s.push(12);
s.push(4);
s.push( s.top() + 2 );
s.pop()
s.push( s.top() );
//what are contents of stack?
![Page 4: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/4.jpg)
4
Stack OperationsWrite a method to print out contents of stack in reverse order.
![Page 5: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/5.jpg)
5
Common Stack ErrorStack s = new Stack();// put stuff in stackfor(int i = 0; i < 7; i++)
s.push( i );// print out contents of stack // while emptying itfor(int i = 0; i < s.size(); i++)
System.out.println( s.pop() );// Output? Why?// Crossover error
![Page 6: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/6.jpg)
6
Corrected VersionStack s = new Stack();// put stuff in stackfor(int i = 0; i < 7; i++)
s.push( i );// print out contents of stack // while emptying itint limit = s.size();for(int i = 0; i < limit; i++)
System.out.println( s.pop() );
//or
// while( !s.isEmpty() )
// System.out.println( s.pop() );
![Page 7: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/7.jpg)
7
Balanced Symbol Checking In processing programs and working with
computer languages there are many instances when symbols must be balanced{ } , [ ] , ( )
A stack is useful for checking symbol balance. When a closing symbol is found it must match the most recent opening symbol of the same type.
Algorithm?
![Page 8: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/8.jpg)
8
Algorithm for Balanced Symbol Checking
Make an empty stack read symbols until end of file
– if the symbol is an opening symbol push it onto the stack
– if it is a closing symbol do the following• if the stack is empty report an error• otherwise pop the stack. If the symbol popped does
not match the closing symbol report an error
At the end of the file if the stack is not empty report an error
![Page 9: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/9.jpg)
9
Algorithm in practice list[i] = 3 * ( 44 - method( foo( list[ 2 * (i + 1) +
foo( list[i - 1] ) ) / 2 *) - list[ method(list[0])];
Processing a file– Tokenization: the process of scanning an input
stream. Each independent chunk is a token.
Tokens may be made up of 1 or more characters
![Page 10: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/10.jpg)
10
Mathematical CalculationsWhat is 3 + 2 * 4? 2 * 4 + 3? 3 * 2 + 4?
The precedence of operators affects the order of operations. A mathematical expression cannot simply be evaluated left to right. A challenge when evaluating a program.Lexical analysis is the process of interpreting a program. Involves Tokenization
What about 1 - 2 - 4 ^ 5 * 3 * 6 / 7 ^ 2 ^ 2
![Page 11: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/11.jpg)
11
Infix and Postfix Expressions The way we are used to writing expressions
is known as infix notation Postfix expression does not require any
precedence rules 3 2 * 1 + is postfix of 3 * 2 + 1 evaluate the following postfix expressions
and write out a corresponding infix expression:2 3 2 4 * + * 1 2 3 4 ^ * +
1 2 - 3 2 ^ 3 * 6 / + 2 5 ^ 1 -
![Page 12: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/12.jpg)
12
Evaluation of Postfix Expressions Easy to do with a stack given a proper postfix expression:
– get the next token– if it is an operand push it onto the stack– else if it is an operator
• pop the stack for the right hand operand• pop the stack for the left hand operand• apply the operator to the two operands• push the result onto the stack
– when the expression has been exhausted the result is the top (and only element) of the stack
![Page 13: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/13.jpg)
13
Infix to Postfix Convert the following equations from infix to
postfix:2 ^ 3 ^ 3 + 5 * 1
2 3 3 ^ ^ 5 1 * +
11 + 2 - 1 * 3 / 3 + 2 ^ 2 / 3
11 2 + 1 3 * 3 / - 2 2 ^ 3 / +
Problems:
parentheses in expression
![Page 14: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/14.jpg)
14
Infix to Postfix Conversion Requires operator precedence parsing algorithm
– parse v. To determine the syntactic structure of a sentence or other utterance
Operands: add to expression
Close parenthesis: pop stack symbols until an open parenthesis appears
Operators:
Pop all stack symbols until a symbol of lower precedence appears. Then push the operator
End of input: Pop all remaining stack symbols and add to the expression
![Page 15: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/15.jpg)
15
Simple ExampleInfix Expression: 3 + 2 * 4
PostFix Expression:
Operator Stack:
![Page 16: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/16.jpg)
16
Simple ExampleInfix Expression: + 2 * 4
PostFix Expression: 3
Operator Stack:
![Page 17: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/17.jpg)
17
Simple ExampleInfix Expression: 2 * 4
PostFix Expression: 3
Operator Stack: +
![Page 18: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/18.jpg)
18
Simple ExampleInfix Expression: * 4
PostFix Expression: 3 2
Operator Stack: +
![Page 19: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/19.jpg)
19
Simple ExampleInfix Expression: 4
PostFix Expression: 3 2
Operator Stack: + *
![Page 20: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/20.jpg)
20
Simple ExampleInfix Expression:
PostFix Expression: 3 2 4
Operator Stack: + *
![Page 21: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/21.jpg)
21
Simple ExampleInfix Expression:
PostFix Expression: 3 2 4 *
Operator Stack: +
![Page 22: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/22.jpg)
22
Simple ExampleInfix Expression:
PostFix Expression: 3 2 4 * +
Operator Stack:
![Page 23: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/23.jpg)
23
Example1 - 2 ^ 3 ^ 3 - ( 4 + 5 * 6 ) * 7
Show algorithm in action on above equation
![Page 24: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/24.jpg)
24
Applications of Stacks Direct applications
– Page-visited history in a Web browser– Undo sequence in a text editor– Chain of method calls in the Java Virtual
Machine– Validate XML
Indirect applications– Auxiliary data structure for algorithms– Component of other data structures
![Page 25: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/25.jpg)
25
Method Stack in the JVM
The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack
When a method is called, the JVM pushes on the stack a frame containing– Local variables and return value– Program counter, keeping track of
the statement being executed When a method ends, its frame
is popped from the stack and control is passed to the method on top of the stack
Allows for recursion
main() {int i = 5;foo(i);}
foo(int j) {int k;k = j+1;bar(k);}
bar(int m) {…}
bar PC = 1 m = 6
foo PC = 3 j = 5 k = 6
main PC = 2 i = 5
![Page 26: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/26.jpg)
26
Implementing a stack need an underlying collection to hold the elements
of the stack 2 basic choices
– array (native or ArrayList)– linked list
array implementation
linked list implementation
Some of the uses for a stack are much more interesting than the implementation of a stack
![Page 27: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/27.jpg)
27
Array-based Stack
A simple way of implementing the Stack ADT uses an array
We add elements from left to right
A variable keeps track of the index of the top element
S0 1 2 t
…
Algorithm size()return t + 1
Algorithm pop()if isEmpty() then
throw EmptyStackException else
t t 1return S[t + 1]
![Page 28: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/28.jpg)
28
Queues
![Page 29: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/29.jpg)
29
Queues Closely related to Stacks Like a line
– In Britain people don’t “get in line” they “queue up”.
Queues are a first in first out data structure– FIFO (or LILO, but that sounds a bit silly)
Add items to the end of the queue Access and remove from the front Used extensively in operating systems
– Queues of processes, I/O requests, and much more
![Page 30: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/30.jpg)
30
Queue operations add(Object item)
– a.k.a. enqueue(Object item)
Object get()– a.k.a. Object front()
Object remove()– a.k.a. Object dequeue()
boolean isEmpty() Specify in an interface, allow varied
implementations
![Page 31: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/31.jpg)
31
Queue Example
Operation Output Q enqueue(5) – (5)enqueue(3) – (5, 3)dequeue() 5 (3)enqueue(7) – (3, 7)dequeue() 3 (7)front() 7 (7)dequeue() 7 ()dequeue() “error” ()isEmpty() true ()enqueue(9) – (9)enqueue(7) – (9, 7)size() 2 (9, 7)enqueue(3) – (9, 7, 3)enqueue(5) – (9, 7, 3, 5)dequeue() 9 (7, 3, 5)
![Page 32: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/32.jpg)
32
Applications of Queues Direct applications
– Waiting lists, bureaucracy– Access to shared resources (e.g., printer)– Multiprogramming
Indirect applications– Auxiliary data structure for algorithms– Component of other data structures
![Page 33: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/33.jpg)
33
Implementation Array-based Queue
Use an array of size N in a circular fashion Two variables keep track of the front and rear
f index of the front elementr index immediately past the rear element
Array location r is kept empty
Q0 1 2 rf
normal configuration
Q0 1 2 fr
wrapped-around configuration
![Page 34: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/34.jpg)
34
Queue Operations
We use the modulo operator (remainder of division)
Algorithm size()return (N f + r) mod N
Algorithm isEmpty()return (f r)
Q0 1 2 rf
Q0 1 2 fr
![Page 35: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/35.jpg)
35
Queue Operations (cont.)
Algorithm enqueue(o)if size() = N 1 then
throw FullQueueException else
Q[r] or (r + 1) mod N
Operation enqueue throws an exception if the array is full
This exception is implementation-dependent
Q0 1 2 rf
Q0 1 2 fr
![Page 36: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/36.jpg)
36
Queue Operations (cont.)
Operation dequeue throws an exception if the queue is empty
This exception is specified in the queue ADT
Algorithm dequeue()if isEmpty() then
throw EmptyQueueException else
o Q[f]f (f + 1) mod Nreturn o
Q0 1 2 rf
Q0 1 2 fr
![Page 37: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/37.jpg)
37
Queue Interface in Java
Java interface corresponding to our Queue ADT
Requires the definition of class EmptyQueueException
No corresponding built-in Java class, however there is PriorityQueue
public interface Queue {
public int size();
public boolean isEmpty();
public Object front()throws EmptyQueueException;
public void enqueue(Object o);
public Object dequeue() throws EmptyQueueException;
}
![Page 38: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/38.jpg)
38
Application: Round Robin Schedulers
We can implement a round robin scheduler using a queue, Q, by repeatedly performing the following steps:
1. e = Q.dequeue()
2. Service element e
3. Q.enqueue(e)
The Queue
Shared Service
1. Deque the next element
3. Enqueue the serviced element
2 . Service the next element
![Page 39: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/39.jpg)
39
Implementing a Queue Given the internal storage container and
choice for front and back of queue what are the Big O of the queue operations?
ArrayList LinkedList LinkedList (Singly Linked) (Doubly
Linked)
enqueue
front
dequeue
isEmpty
![Page 40: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/40.jpg)
40
Priority Queue ImplementationSequence-based Priority Queue
Implementation with an unsorted list
Performance:– insert takes O(1) time
since we can insert the item at the beginning or end of the sequence
– removeMin and min take O(n) time since we have to traverse the entire sequence to find the smallest key
Implementation with a sorted list
Performance:– insert takes O(n) time
since we have to find the place where to insert the item
– removeMin and min take O(1) time, since the smallest key is at the beginning
4 5 2 3 1 1 2 3 4 5
![Page 41: Stack and Queue](https://reader034.vdocument.in/reader034/viewer/2022051019/5695d4071a28ab9b02a0047d/html5/thumbnails/41.jpg)
41
Priority Queue Applications Priority-based OS process scheduler