CS 12 StacksQueues
CS 12 StacksQueues
S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
Computer Science
ROBERT SEDGEWICK
K E V I N WAY N E
Section 4.3
http://introcs.cs.princeton.edu
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
CS.12.A.StacksQueues.APIs
Data types and data structures
Data types
• Set of values.
• Set of operations on those values.
• Some are built in to Java: int, double, String, . . .
• Most are not: Complex, Picture, Charge, . . .
Data structures
• Represent data.
• Represent relationships among data.
• Some are built in to Java: 1D arrays, 2D arrays, . . .
• Most are not: linked list, circular list, tree, . . .
Design challenge for every data type: Which data structure to use?
• Resource 1: How much memory is needed?
• Resource 2: How much time do data-type methods use?
3
Stack and Queue APIs
A collection is an ADT whose values are a multiset of items, all of the same type.
Two fundamental collection ADTs differ in just a detail of the specification of their operations.
• Return the size of the collection. • Return the size of the collection.
Add to
Stacks and queues both arise naturally in countless applications. the end
4
Example of stack operations
push to pop from
the top the top
to be
not not not not not that
stack
contents or or or or or or or or or
after be be be be be be be be be be be is
operation
to to to to to to to to to to to to to to
5
Example of queue operations
dequeue from
the beginning
enqueue at
the end
RS+KW. Implementations that do not meet performance specs do not implement the abstractions.
8
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
CS.12.A.StacksQueues.APIs
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
CS.12.B.StacksQueues.Clients
Stack and queue applications
Queues
• First-come-first-served resource allocation.
• Asynchronous data transfer (StdIn, StdOut).
• Dispensing requests on a shared resource.
• Simulations of the real world.
Stacks
• Last-come-first-served resource allocation.
• Function calls in programming languages.
• Basic mechanism in interpreters, compilers.
• Fundamental abstraction in computing.
11
Queue client example: Read all strings from StdIn into an array
Typical scenario
• Visit a page.
• Click a link to another page.
• Click a link to another page.
• Click a link to another page.
• Click "back" button.
• Click "back" button.
• Click "back" button.
http://introcs.cs.princeton.edu/java/43stack/
http://introcs.cs.princeton.edu/java/40algorithms/
http://introcs.cs.princeton.edu/java/home/
14
Autoboxing
15
Stack client example: Postfix expression evaluation
Infix. Standard way of writing arithmetic expressions, using parentheses for precedence.
1 2 3 + 4 5 * * +
find first operator, convert
There is only one 1 (2+3)4 5 * * +
way to parenthesize to infix, enclose in ()
HP-35 (1972)
a postfix expression. 1 ((2+3)*(4*5))+ First handheld calculator.
iterate, treating subexpressions "Enter" means "push".
in parentheses as atomic No parentheses.
(1+((2+3)*(4*5)))
Algorithm
• While input stream is nonempty, read a token.
• Value: Push onto the stack.
• Operator: Pop operand(s), apply operator, push the result.
1 2 3 + 4 5 * * +
1 2 3 + 4 5 * * +
= 5 = 20 = 101
= 100 5
3 4 4 20
2 2 5 5 5 5 100
1 1 1 1 1 1 1 1 101
17
Stack client example: Postfix expression evaluation
300
PostScript (Warnock-Geschke, 1980s): A turtle with a stack.
100
• Postfix program code (push literals; functions pop arguments).
• Add commands to drive virtual graphics machine.
• Add loops, conditionals, functions, types, fonts, strings....
Image sources
http://pixabay.com/en/book-stack-learn-knowledge-library-168824/
http://upload.wikimedia.org/wikipedia/commons/2/20/Cars_in_queue_to_enter_Gibraltar_from_Spain.jpg
CS.12.B
A.StacksQueues.C
AlPi
Iesnts
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
CS.12.C.StacksQueues.Strawman
Strawman ADT for pushdown stacks
values
instance variables
Data structure choice. Use an array to hold the collection. constructor
methods
23
Strawman stack implementation: Test client
instance variables
constructors
public static void main(String[] args)
{
int max = Integer.parseInt(args[0]); methods
24
Pop quiz 1 on stacks
Q. Can we always insert pop() commands to make items come out in sorted order?
Example 1. 6 5 4 3 2 1 - - - - - -
Example 2. 1 - 2 - 3 - 4 - 5 - 6 -
Example 3. 4 1 - 3 2 - - - 6 5 - -
1 2 3 4 5 6
2
1 3 3 3 5
4 4 4 4 4 4 4 6 6 6
25
Strawman implementation: Methods
instance variables
Methods define data-type operations (implement APIs). constructors
after
public class StrawStack push() methods
{
...
public boolean isEmpty()
{ return (N == 0); } test client
26
Strawman pushdown stack implementation
28
Benchmarking the strawman stack implementation
StrawStack implements a fixed-capacity collection that behaves like a stack if the data fits.
It does not implement the stack API or meet the performance specifications.
CS.12.C.StacksQueues.Strawman
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
CS.12.D.StacksQueues.Lists
Data structures: sequential vs. linked
C3 C3
C4 C4 "Alice"
Linked data structure C5 C5 CA
• Associate with each object a link to another one. C6 C6
• Machine: link is memory address of next object.
C7 C7
• Java: link is reference to next object.
C8 C8
• Variable size, sequential access. next element
C9 C9
• Overlooked by novice programmers.
• Flexible, widely used method for organizing data. CA CA "Bob"
CB CB C0
32
Simplest singly-linked data structure: linked list
Linked list
• A recursive data structure. private class Node
• Def. A linked list is null or a reference to a node. {
private String item;
• Def. A node is a data type that contains a reference to a node. private Node next;
}
• Unwind recursion: A linked list is a sequence of nodes.
Representation
• Use a private nested class Node to implement the node abstraction.
• For simplicity, start with nodes having two values: a String and a Node.
A linked list
Even with just one link ( ) a wide variety of data structures are possible.
Tree
Linked list (this lecture)
Rho
C7
C8
C9
first second third
CA "Bob"
An operation that calls for a doubly-linked list (slightly beyond our scope)
• Remove and return the node at the end.
36
List processing code: Remove and return the first item
item
item = first.item;
"Alice" first "Alice" "Bob" "Carol"
item
first = first.next; "Alice" first "Alice" "Bob" "Carol"
available for
garbage collection
item
return item; "Alice" first "Bob" "Carol"
37
List processing code: Add a new node at the beginning
second
second
second
38
List processing code: Traverse a list
Node x = first;
x
while (x != null)
{
first "Alice" "Bob" "Carol"
StdOut.println(x.item);
x = x.next;
}
Alice
StdOut Bob
Carol
39
Pop quiz 1 on linked lists
...
Node list = null;
while (!StdIn.isEmpty())
{
Node old = list;
list = new Node();
list.item = StdIn.readString();
list.next = old;
}
for (Node t = list; t != null; t = t.next)
StdOut.println(t.item);
...
40
Pop quiz 2 on stacks
Q. Give code that uses a stack to print the strings from StdIn on StdOut, in reverse order.
41
Pop quiz 2 on linked lists
...
Node list = new Node();
list.item = StdIn.readString();
Node last = list;
while (!StdIn.isEmpty())
{
last.next = new Node();
last = last.next;
last.item = StdIn.readString();
}
...
42
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
CS.12.D.StacksQueues.Lists
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
CS.12.E.StacksQueues.Implementations
Pushdown stack implementation: Instance variables and constructor
Data structure choice. Use a linked list to hold the collection. instance variables
constructor
45
Stack implementation: Test client
instance variables
constructors
public static void main(String[] args)
{
Stack<String> stack = new Stack<String>(); methods
while (!StdIn.isEmpty())
{
String item = StdIn.readString(); test client
if (item.equals("-"))
System.out.print(stack.pop() + " ");
else
stack.push(item);
}
StdOut.println();
} % more tobe.txt
to be or not to - be - - that - - - is
46
Stack implementation: Methods
instance variables
Methods define data-type operations (implement the API). constructors
Push to the
beginning
push pop
to to
be be to
or or be to
not not or be to
to to not or be to
- to not or be to
be be not or be to
- be not or be to
- not or be to
that that or be to
- that or be to
- or be to
- be to
is is to
Item pop() remove and return the item most recently pushed
Also possible to implement the queue abstraction with a singly-linked list (see text).
50
Summary
push to the pop from the dequeue from
Stacks and queues beginning beginning the beginning
enqueue at
the end
Linked structures
• Fundamental alternative to arrays.
• Enable implementations of the stack/queue abstractions
that meet performance specifications.
CS.12.E.StacksQueues.Implementations
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
Computer Science
ROBERT SEDGEWICK
K E V I N WAY N E
Section 4.3
http://introcs.cs.princeton.edu