0% found this document useful (0 votes)
15 views53 pages

CS 12 StacksQueues

Uploaded by

Devharsh Trivedi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views53 pages

CS 12 StacksQueues

Uploaded by

Devharsh Trivedi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

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

Computer 12. Stacks and Queues


ScienceAn Interdisciplinary Approach

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

12. Stacks and Queues


• APIs
• Clients
• Strawman implementation
• Linked lists
• Implementations

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.

Add to the Take from the Take from the


beginning beginning beginning
Stack operations Queue operations
• Add an item to the collection. • Add an item to the collection.
• Remove and return the item Last • Remove and return the item First
In
most recently added (LIFO). In least recently added (FIFO). First
First
• Test if the collection is empty. Out • Test if the collection is empty. Out

• 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

A key characteristic. No limit on the size of the collection.

4
Example of stack operations
push to pop from
the top the top

Push. Add an item to the collection.


Pop. Remove and return the item most recently added. Last
In
First
push to Out
the top
pop from
the top

push to be or not to - be - - that - - - is


pop to be not that or be

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. Add an item to the collection.


First
Dequeue. Remove and return the item least recently added. In
First
Out

enqueue at
the end

enqueue to be or not to - be - - that - - - is


dequeue to be or not to be
dequeue from the beginning

to to to to to be be or not not to be that that


queue be be be be or or not to to be that is
contents
or or or not not to be be that
after
operation not not to to be that
enqueue at
the end to be
6
Parameterized data types
Goal. Simple, safe, and clear client code for collections of any type of data.

Java approach: Parameterized data types (generics)


• Use placeholder type name in definition.
• Substitute concrete type for placeholder in clients. stay tuned for examples

public class Stack<Item>


Stack<Item>() create a stack of items, all of type Item
void push(Item item) add item to stack
Stack API
Item pop() remove and return the item most recently pushed
boolean isEmpty() is the stack empty ?
int size() # of objects on the stack

public class Queue<Item>


Queue<Item>() create a queue of items, all of type Item
void enqueue(Item item) add item to queue
Queue API
Item dequeue() remove and return the item least recently enqueued
boolean isEmpty() is the queue empty ?
int size() # of objects on the queue
7
Performance specifications

Challenge. Provide guarantees on performance.

Goal. Simple, safe, clear, and efficient client code.


Typically required for
client code to be scalable

• All operations are constant-time.


Performance • Memory use is linear in the size of the
specifications collection, when it is nonempty.
• No limits within the code on the collection size.

Java. Any implementation of the API implements the stack/queue abstractions.

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

12. Stacks and Queues


• APIs
• Clients
• Strawman implementation
• Linked lists
• Implementations

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

public class QEx Note: StdIn has this


functionality
{
public static String[] readAllStrings()
Challenge { /* See next slide. */ }
• Can’t store strings in array
before creating the array. public static void main(String[] args)
{
• Can’t create the array without
String[] words = readAllStrings();
knowing how many strings are for (int i = 0; i < words.length; i++)
in the input stream. StdOut.println(words[i]);
• Can’t know how many strings }
are in the input stream without }
% java QEx < moby.txt
reading them all. moby
Solution: Use a Queue<String>. % more moby.txt dick
moby dick herman
herman melville melville
call me ishmael some years ago never call
mind how long precisely having me
little or no money ishmael
... some
years
...
12
Queue client example: Read all strings from StdIn into an array

public class QEx


{
public static String[] readAllStrings()
Solution: Use a Queue<String>. {
• Store strings in the queue. Queue<String> q = new Queue<String>();
• Get the size when all have been while (!StdIn.isEmpty())
q.enqueue(StdIn.readString());
read from StdIn.
int N = q.size();
• Create an array of that size. String[] words = new String[N];
• Copy the strings into the array. for (int i = 0; i < N; i++)
words[i] = q.dequeue();
return words;
}
public static void main(String[] args)
{
String[] words = readAllStrings();
for (int i = 0; i < words.length; i++)
StdOut.println(words[i]);
}
}
13
Stack example: "Back" button in a browser

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

Challenge. Use a primitive type in a parameterized ADT.

Wrapper types primitive type wrapper type


• Each primitive type has a wrapper reference type. int Integer
• Wrapper type has larger set of operations than primitive type.
char Character
Example: Integer.parseInt().
double Double
• Instances of wrapper types are objects.
• Wrapper type can be used in a parameterized ADT. boolean Boolean

Autoboxing. Automatic cast from primitive type to wrapper type.

Auto-unboxing. Automatic cast from wrapper type to primitive type.

Stack<Integer> stack = new Stack<Integer>();


Simple client code stack.push(17); // Autobox (int -> Integer)
(no casts)
int a = stack.pop(); // Auto-unbox (Integer -> int)

15
Stack client example: Postfix expression evaluation

Infix. Standard way of writing arithmetic expressions, using parentheses for precedence.

Example. ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) = ( 1 + ( 5 * 20) ) = 101

Postfix. Write operator after operands (instead of in between them).

Example. 1 2 3 + 4 5 * * + also called "reverse Polish" notation (RPN) Jan Łukasiewicz


1878−1956

Remarkable fact. No parentheses are needed!

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)))

Next. With a stack, postfix expressions are easy to evaluate.


Made slide rules obsolete (!)
16
Postfix arithmetic expression evaluation

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

public class Postfix


{ % java Postfix
public static void main(String[] args) 1 2 3 + 4 5 * * +
{ 101.0
Stack<Double> stack = new Stack<Double>();
while (!StdIn.isEmpty())
{
String token = StdIn.readString();
if (token.equals("*")) % java Postfix
1 5 sqrt + 2 /
+
stack.push(stack.pop() * stack.pop());
1.618033988749895
else if (token.equals("+"))
stack.push(stack.pop() + stack.pop());
else if (token.equals("-"))
stack.push(-stack.pop() + stack.pop());
else if (token.equals("/"))
stack.push((1.0/stack.pop()) * stack.pop());
else if (token.equals("sqrt"))
Perspective
stack.push(Math.sqrt(stack.pop())); • Easy to add operators of all sorts.
else
stack.push(Double.parseDouble(token));
• Can do infix with two stacks (see text).
} • Could output machine language code.
StdOut.println(stack.pop()); • Indicative of how Java compiler works.
}
}
18
Real-world stack application: PostScript

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....

push(100) call "moveto" (takes args from stack)


PostScript code 100 100 moveto
100 300 lineto
define a path
300 300 lineto
300 100 lineto
stroke draw the path

A simple virtual machine, but not a toy


• Easy to specify published page.
• Easy to implement on various specific printers.
• Revolutionized world of publishing.

Another stack machine: The JVM ( Java Virtual Machine)!


19
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

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

12. Stacks and Queues


• APIs
• Clients
• Strawman implementation
• Linked lists
• Implementations

CS.12.C.StacksQueues.Strawman
Strawman ADT for pushdown stacks

Warmup: simplify the ADT


• Implement only for items of type String.
• Have client provide a stack capacity in the constructor.

values

public class StrawStack

StrawStack(int max) create a stack of capacity max


void push(String item) add item to stack
Strawman API
String pop() return the string most recently pushed
boolean isEmpty() is the stack empty ?
int size() number of strings on the stack

Rationale. Allows us to represent the collection with an array of strings.


22
Strawman implementation: Instance variables and constructor

instance variables
Data structure choice. Use an array to hold the collection. constructor

methods

public class StrawStack test client


{ a[0]
private String[] a; a[1]
items on stack
private int N = 0; a[2]
...
public StrawStack(int max) N
{ a = new String[max]; }
... "upside down"
} representation of

23
Strawman stack implementation: Test client

instance variables
constructors
public static void main(String[] args)
{
int max = Integer.parseInt(args[0]); methods

StrawStack stack = new StrawStack(max);


while (!StdIn.isEmpty())
{ test client
String item = StdIn.readString();
if (item.equals("-"))
StdOut.print(stack.pop());
else
stack.push(item);
}
StdOut.println(); % more tobe.txt
} to be or not to - be - - that - - - is

% java StrawStack 20 < tobe.txt


to be not that or be

What we expect, once the implementation is done.

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

public void push(String item)


{ a[N++] = item; } N
public String pop()
{ return a[--N]; }
after
public int size() N pop()
{ return N; }
... all constant-time
} one-liners!
N

26
Strawman pushdown stack implementation

public class StrawStack


{
private String[] a;
private int N = 0; instance variables
public StrawStack(int max)
{ a = new String[max]; } constructor
public boolean isEmpty()
{ return (N == 0); }
public void push(String item)
{ a[N++] = item; } methods
public String pop()
{ return a[--N]; }
% more tobe.txt
public int size()
{ return N; } to be or not to - be - - that - - - is
public static void main(String[] args)
{ % java StrawStack 20 < tobe.txt
int max = Integer.parseInt(args[0]); to be not that or be
StrawStack stack = new StrawStack(max);
while (!StdIn.isEmpty())
{
String item = StdIn.readString(); test client
if (item.equals("-"))
StdOut.print(stack.pop() + " ");
else
stack.push(item);
}
StdOut.println();
}
}
27
Trace of strawman stack implementation (array representation)

push to be or not to - be - - that - - - is


pop to be not that or be
a[0] to to to to to to to to to to to to to to
a[1] be be be be be be be be be be be be is
a[2] or or or or or or or or or or or or
a[3] N not not not not not not that that that that that
a[4] to to be be be be be be be be
a[5]
a[6]
stack a[7]
contents a[8]
after a[9]
operation a[10]
a[11]
Significant wasted space when stack size
a[12] is not near the capacity (typical).
a[13]
a[14]
a[15]
a[16]
a[17]
a[18]
a[19]

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.

StrawStack requires client to provide capacity


Stack API public class Stack<Item>

Stack<Item>() ✘ create a stack of items, all of type Item


void push(Item item) add item to stack
StrawStack
works only ✘ Item pop() remove and return the item most recently pushed
for strings boolean isEmpty() is the stack empty ?

int size() # of items on the stack

• All operations are constant-time. ✓


Performance • Memory use is linear in the size of the collection,
specifications
when it is nonempty. ✘
• No limits within the code on the collection size. ✘

Nice try, but need a new data structure.


29
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.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

12. Stacks and Queues


• APIs
• Clients
• Strawman implementation
• Linked lists
• Implementations

CS.12.D.StacksQueues.Lists
Data structures: sequential vs. linked

Array at C0 Linked list at C4


Sequential data structure
addr value addr value
• Put objects next to one another.
C0 "Alice" C0 "Carol"
• Machine: consecutive memory cells.
• Java: array of objects. C1 "Bob" C1 null

• Fixed size, arbitrary access. i th element C2 "Carol" C2

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

first "Alice" "Bob" "Carol"


null
item next
33
Singly-linked data structures

Even with just one link ( ) a wide variety of data structures are possible.

Tree
Linked list (this lecture)
Rho

Circular list (TSP) General case

From the point of view of a particular object,


all of these structures look the same.
Multiply linked structures: many more possibilities!
34
Building a linked list

Node third = new Node();


addr value
third.item = "Carol";
third.next = null; C0 "Carol"

Node second = new Node(); C1 null


second.item = "Bob"; C2
second.next = third;
C3
third C0
Node first = new Node();
C4 "Alice"
first.item = "Alice"; second CA
first.next = second; C5 CA
first C4
C6

C7

C8

C9
first second third
CA "Bob"

"Alice" "Bob" "Carol" CB C0


null
35
List processing code

Standard operations for processing data structured as a singly-linked list


• Add a node at the beginning.
• Remove and return the node at the beginning.
• Add a node at the end (requires a reference to the last node).
• Traverse the list (visit every node, in sequence).

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

Goal. Remove and return the first


item in a linked list first.
first "Alice" "Bob" "Carol"

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

Goal. Add item to a linked list first. item


"Dave"

first "Alice" "Bob" "Carol"

second

Node second = first;


first "Alice" "Bob" "Carol"

second

first = new Node(); first "Alice" "Bob" "Carol"

second

first.item = item; first "Dave" "Alice" "Bob" "Carol"


first.next = second;

38
List processing code: Traverse a list

Goal. Visit every node on a linked list first.

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

Q. What is the effect of the following code (not-so-easy question)?

...
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

Q. What is the effect of the following code (not-so-easy question)?

...
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

14. Stacks and Queues


• APIs
• Clients
• Strawman implementation
• Linked lists
• Implementations

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

public class Stack<Item>


methods
{
private Node first = null;
private int N = 0;
test client

private class Node use in place of concrete type


{ objects on stack
private Item item;
private Node next;
}
... first
}

Annoying exception (not a problem here).


Can't declare an array of Item objects (don't ask why).
Need cast: Item[] a = (Item[]) new Object[N]

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

% java Stack < tobe.txt


to be not that or be

What we expect, once the implementation is done.

46
Stack implementation: Methods

instance variables
Methods define data-type operations (implement the API). constructors

public class Stack<Item> methods


{
... might also use N == 0
public boolean isEmpty()
{ return first == null; }
test client
public void push(Item item)
{
Node second = first; instance
first = new Node(); variable
first.item = item;
first.next = second;
N++; add a new node first
} to the beginning of the list
first
public Item pop()
{ local variable
second in push()
Item item = first.item;
first = first.next;
N--;
return item;
} remove and return first
public int size() first item on list
first
{ return N; }
...
}
47
Stack implementation

public class Stack<Item>


{
private Node first = null;
private int N = 0; instance variables
private class Node
{
private Item item; nested class
private Node next;
}
public boolean isEmpty()
{ return first == null; }
public void push(Item item)
{
Node second = first;
% more tobe.txt
first = new Node();
first.item = item; to be or not to - be - - that - - - is
first.next = second;
N++; % java Stack < tobe.txt
} methods to be not that or be
public Item pop()
{
Item item = first.item;
first = first.next;
N--;
return item;
}
public int size()
{ return N; }
public static void main(String[] args)
{ // See earlier slide } test client
}
48
Trace of stack implementation (linked list representation)

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

Pop from the


beginning 49
Benchmarking the stack implementation

Stack implements the stack abstraction.

It does implement the API and meet the performance specifications.

Stack API public class Stack<Item>

Stack<Item>() create a stack of items, all of type Item

void push(Item item) add item to stack

Item pop() remove and return the item most recently pushed

boolean isEmpty() is the stack empty ?

int size() # of items on the stack ✓


• All operations are constant-time. ✓
Performance • Memory use is linear in the size of the collection,
specifications
when it is nonempty. ✓
• No limits within the code on the collection size. ✓
dequeue(): same code as pop()
enqueue(): slightly more complicated
Made possible by linked data structure.

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

• Fundamental collection abstractions.


• Differ only in order in which items are removed. Last First
In
In
• Performance specifications: Constant-time for all stack
First
queue First
operations and space linear in the number of objects. Out Out

enqueue at
the end

Linked structures
• Fundamental alternative to arrays.
• Enable implementations of the stack/queue abstractions
that meet performance specifications.

Next: Symbol tables


51
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.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

Computer 12. Stacks and Queues


ScienceAn Interdisciplinary Approach

ROBERT SEDGEWICK
K E V I N WAY N E
Section 4.3

http://introcs.cs.princeton.edu

You might also like