02 Stack Queue
02 Stack Queue
Stack.
• Remove the item most recently added.
! stacks • Analogy: cafeteria trays, Web surfing.
FIFO = "first in first out"
! dynamic resizing Queue.
! queues • Remove the item least recently added.
! generics • Analogy: Registrar's line.
! applications push
pop
enqueue dequeue
1 2
Interface: description of data type, basic operations. Interface: description of data type, basic operations.
Client: program using operations defined in interface. Client: program using operations defined in interface.
Implementation: actual code implementing operations. Implementation: actual code implementing operations.
3 4
Stacks
Stack operations.
• push() Insert a new item onto stack.
• pop() Remove and return the item most recently added.
• isEmpty() Is the stack empty? push
pop
! dynamic resizing
{
String s = StdIn.readString();
! queues stack.push(s);
! generics
}
while(!stack.isEmpty())
! applications {
String s = stack.pop();
StdOut.println(s);
}
}
a sample stack client
5 6
first
first
best the was it second = first;
7 8
Stack: Linked-list implementation Stack: Array implementation
9 10
11 12
Stack array implementation: Dynamic resizing Stack array implementation: Dynamic resizing
•
{ this(8); }
pop() : decrease size of s[] by 1 constructor
public void push(String item)
{
Too expensive if (N >= s.length) resize();
• Need to copy all of the elements to a new array. s[N++] = item;
•
}
Inserting N elements: time proportional to 1 + 2 + … + N " N2/2.
private void resize(int max)
{
create new array
infeasible for large N copy items to it
String[] dup = new String[max];
for (int i = 0; i < N; i++)
dup[i] = s[i];
s = dup;
}
Need to guarantee that array resizing happens infrequently Consequence. Inserting N items takes time proportional to N (not N2).
13 8 + 16 + … + N/4 + N/2 + N " 2N 14
Stack array implementation: Dynamic resizing Stack Implementations: Array vs. Linked List
17 18
Queue operations.
• enqueue() Insert a new item onto queue. first last
first last
public static void main(String[] args) was the best of first = first.next;
{
QueueOfStrings q = new QueueOfStrings();
q.enqueue("Vertigo"); last
first
q.enqueue("Just Lose It");
q.enqueue("Pieces of Me");
was the best of return item;
q.enqueue("Pieces of Me");
System.out.println(q.dequeue());
q.enqueue("Drop It Like It's Hot");
while(!q.isEmpty()
System.out.println(q.dequeue());
} Aside:
dequeue (pronounced “DQ”) means “remove from a queue”
deque (pronounced “deck”) is a data structure (see PA 1)
19 20
Enqueue: Linked List Implementation Queue: Linked List Implementation
23 24
Generics (parameterized data types) Stack of Objects
We also want: StackOfURLs, QueueOfCustomers, etc? We also want: StackOfURLs, QueueOfCustomers, etc?
Attempt 1. Implement a separate stack class for each type. Attempt 2. Implement a stack with items of type Object.
• Rewriting code is tedious and error-prone. • Casting is required in client.
• Maintaining cut-and-pasted code is tedious and error-prone. • Casting is error-prone: run-time error if types mismatch.
@#$*! most reasonable approach until Java 1.5 [hence, used in AlgsJava]
25 26
Why? } }
27 28
Generic stack: array implementation Generic stack: array implementation
The way it should be. The way it is: an ugly cast in the implementation.
public void push(Item item) public void push(String item) public void push(Item item)
{ s[N++] = item; } { s[N++] = item; } { s[N++] = item; }
} } }
Wrapper type.
•Each primitive type has a wrapper object type.
•Ex: Integer is wrapper type for int.
Autoboxing. Automatic cast between a primitive type and its wrapper. ! stacks
Syntactic sugar. Behind-the-scenes casting.
! dynamic resizing
! queues
Stack<Integer> s = new Stack<Integer>(); ! generics
! applications
s.push(17); // s.push(new Integer(17));
int a = s.pop(); // int a = ((int) s.pop()).intValue();
Bottom line: Client code can use generic stack for any type of data
31 32
Stack Applications Function Calls
•
else if (s.equals("+")) ops.push(s);
Operator: push onto the operator stack. else if (s.equals("*")) ops.push(s);
• Left parens: ignore. else if (s.equals(")")) {
35 Note: Old books have two-pass algorithm because generics were not available! 36
Correctness Stack-based programming languages
( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
( 1 ( ( 2 3 + ) ( 4 5 * ) * ) + )
as if the original input were:
Observation 2.
( 1 + ( 5 * ( 4 * 5 ) ) )
All of the parentheses are redundant!
Repeating the argument:
1 2 3 + 4 5 * * +
( 1 + ( 5 * 20 ) )
( 1 + 100 ) Jan Lukasiewicz
101
37 38
%!
72 72 moveto
a PostScript program %!
0 72 rlineto
/Helvetica-Bold findfont 16 scalefont setfont
72 0 rlineto
72 168 moveto
0 -72 rlineto
(Square root of 2:) show
-72 0 rlineto
72 144 moveto
2 setlinewidth
2 sqrt 10 string cvs show
stroke
39 40
Stack-based programming languages: PostScript Stack-based programming languages: PostScript
43 44
M/D/1 queuing model M/D/1 queuing model: example
M/D/1 queue.
• Customers are serviced at fixed rate of µ per minute.
• Customers arrive according to Poisson process at rate of # per minute.
inter-arrival time has exponential distribution
Pr[X " x] = 1# e# $x
45 46
M/D/1 queuing model: experiments and analysis M/D/1 queuing model: event-based simulation