SlideShare a Scribd company logo
http://introcs.cs.princeton.edu
R O B E R T S E D G E W I C K
K E V I N W A Y N E
ComputerScience
Computer
ScienceAn Interdisciplinary Approach
12. Stacks and Queues
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART II: ALGORITHMS, THEORY, AND MAC HINES
Section 4.3
12. Stacks and Queues
•APIs
•Clients
•Strawman implementation
•Linked lists
•Implementations
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART II: ALGORITHMS, THEORY, AND MAC HINES
CS.12.A.StacksQueues.APIs
Data types and data structures
3
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?
Stack and Queue APIs
4
Stack operations
• Add an item to the collection.
• Remove and return the item
most recently added (LIFO).
• Test if the collection is empty.
• Return the size of the collection.
Two fundamental collection ADTs differ in just a detail of the specification of their operations.
A collection is an ADT whose values are a multiset of items, all of the same type.
Queue operations
• Add an item to the collection.
• Remove and return the item
least recently added (FIFO).
• Test if the collection is empty.
• Return the size of the collection.
Stacks and queues both arise naturally in countless applications.
A key characteristic. No limit on the size of the collection.
Add to the
beginning
Add to
the end
Take from the
beginning
Last
In
First
Out
Take from the
beginning
First
In
First
Out
Example of stack operations
5
Push. Add an item to the collection.
Pop. Remove and return the item most recently added.
push to be or not to - be - - that - - - is
pop
stack
contents
after
operation
push to
the top
pop from
the top
Last
In
First
Out
to
be
to
or
be
to
not
or
be
to
to
not
or
be
to
push to
the top
be
not
or
be
to
that
or
be
to
is
to
pop from

the top
to
not
or
be
to
be
not
or
be
to
not
or
be
to
that
or
be
to
or
be
to
be
to
Example of queue operations
6
Enqueue. Add an item to the collection.
Dequeue. Remove and return the item least recently added.
to to
be
to
be
or
to
be
or
not
to
be
or
not
to
be
or
not
to
be
not
to
be
that
that
is
enqueue to be or not to - be - - that - - - is
dequeue
queue
contents
after
operation
enqueue at
the end
dequeue from
the beginning
First
In
First
Out
enqueue at
the end
dequeue from the beginning
to
be
or
not
to
be
or
not
to
be
or
not
to
be
not
to
be
that
to
be
that
be
that
Java approach: Parameterized data types (generics)
• Use placeholder type name in definition.
• Substitute concrete type for placeholder in clients.
Parameterized data types
7
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 objects on the stack
Stack API
public class Queue<Item>
Queue<Item>() create a queue of items, all of type Item
void enqueue(Item item) add item to queue
Item dequeue() remove and return the item least recently enqueued
boolean isEmpty() is the queue empty ?
int size() # of objects on the queue
Queue API
Goal. Simple, safe, and clear client code for collections of any type of data.
stay tuned for examples
Performance specifications
8
• All operations are constant-time.
• Memory use is linear in the size of the
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.
Goal. Simple, safe, clear, and efficient client code.
Challenge. Provide guarantees on performance.
Performance
specifications
Typically required for
client code to be scalable
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.12.A.StacksQueues.APIs
12. Stacks and Queues
•APIs
•Clients
•Strawman implementation
•Linked lists
•Implementations
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART II: ALGORITHMS, THEORY, AND MAC HINES
CS.12.B.StacksQueues.Clients
Stack and queue applications
11
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.
Queue client example: Read all strings from StdIn into an array
public class QEx
{
public static String[] readAllStrings()
{ /* See next slide. */ }
public static void main(String[] args)
{
String[] words = readAllStrings();
for (int i = 0; i < words.length; i++)
StdOut.println(words[i]);
}
}
12
Challenge
• Can’t store strings in array
before creating the array.
• Can’t create the array without
knowing how many strings are
in the input stream.
• Can’t know how many strings
are in the input stream without
reading them all.
Solution: Use a Queue<String>. % more moby.txt
moby dick
herman melville
call me ishmael some years ago never
mind how long precisely having
little or no money
...
% java QEx < moby.txt
moby
dick
herman
melville
call
me
ishmael
some
years
...
Note: StdIn has this
functionality
Queue client example: Read all strings from StdIn into an array
public class QEx
{
public static String[] readAllStrings()
{
Queue<String> q = new Queue<String>();
while (!StdIn.isEmpty())
q.enqueue(StdIn.readString());
int N = q.size();
String[] words = new String[N];
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
Solution: Use a Queue<String>.
• Store strings in the queue.
• Get the size when all have been
read from StdIn.
• Create an array of that size.
• Copy the strings into the array.
Stack example: "Back" button in a browser
14
http://introcs.cs.princeton.edu/java/home/
http://introcs.cs.princeton.edu/java/40algorithms/
http://introcs.cs.princeton.edu/java/43stack/
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.
Autoboxing
15
Wrapper types
• Each primitive type has a wrapper reference type.
• Wrapper type has larger set of operations than primitive type.

Example: Integer.parseInt().
• Instances of wrapper types are objects.
• Wrapper type can be used in a parameterized ADT.
Autoboxing. Automatic cast from primitive type to wrapper type.
Challenge. Use a primitive type in a parameterized ADT.
primitive type wrapper type
int Integer
char Character
double Double
boolean Boolean
Auto-unboxing. Automatic cast from wrapper type to primitive type.
Simple client code
(no casts)
Stack<Integer> stack = new Stack<Integer>();
stack.push(17); // Autobox (int -> Integer)
int a = stack.pop(); // Auto-unbox (Integer -> int)
Stack client example: Postfix expression evaluation
16
Example. 1 2 3 + 4 5 * * +
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).
There is only one
way to parenthesize
a postfix expression.
Next. With a stack, postfix expressions are easy to evaluate.
1 ( 2 + 3 ) 4 5 * * +
1 2 3 + 4 5 * * +
Remarkable fact. No parentheses are needed!
find first operator, convert
to infix, enclose in ()
1 ( ( 2 + 3 ) * ( 4 * 5 ) ) + iterate, treating subexpressions
in parentheses as atomic
( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
also called "reverse Polish" notation (RPN) Jan ukasiewicz
1878⇥1956
HP-35 (1972)

First handheld calculator.
"Enter" means "push".
No parentheses.
Made slide rules obsolete (!)
= =
+
Postfix arithmetic expression evaluation
17
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 * *
5= 20= 100 101
1 2 3 + 4 5 * * +
1 1011
2
1
2
3
1
5
1
5
4
1
5
4
5
1
5
20
1
100
Stack client example: Postfix expression evaluation
public class Postfix
{
public static void main(String[] args)
{
Stack<Double> stack = new Stack<Double>();
while (!StdIn.isEmpty())
{
String token = StdIn.readString();
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(-stack.pop() + stack.pop());
else if (token.equals("/"))
stack.push((1.0/stack.pop()) * stack.pop());
else if (token.equals("sqrt"))
stack.push(Math.sqrt(stack.pop()));
else
stack.push(Double.parseDouble(token));
}
StdOut.println(stack.pop());
}
}
18
% java Postfix
1 2 3 + 4 5 * * +
101.0
% java Postfix
1 5 sqrt + 2 /
1.618033988749895
+
Perspective
• Easy to add operators of all sorts.
• Can do infix with two stacks (see text).
• Could output machine language code.
• Indicative of how Java compiler works.
100 100 moveto
100 300 lineto
300 300 lineto
300 100 lineto
stroke
Real-world stack application: PostScript
19
PostScript (Warnock-Geschke, 1980s): A turtle with a stack.
• Postfix program code (push literals; functions pop arguments).
• Add commands to drive virtual graphics machine.
• Add loops, conditionals, functions, types, fonts, strings....
A simple virtual machine, but not a toy
• Easy to specify published page.
• Easy to implement on various specific printers.
• Revolutionized world of publishing.
100
300
Another stack machine: The JVM (Java Virtual Machine)!
push(100)
PostScript code
define a path
draw the path
call "moveto" (takes args from stack)
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.12.A.StacksQueues.APIsCS.12.B.StacksQueues.Clients
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
12. Stacks and Queues
•APIs
•Clients
•Strawman implementation
•Linked lists
•Implementations
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART II: ALGORITHMS, THEORY, AND MAC HINES
CS.12.C.StacksQueues.Strawman
Warmup: simplify the ADT
• Implement only for items of type String.
• Have client provide a stack capacity in the constructor.
Strawman ADT for pushdown stacks
22
public class StrawStack
StrawStack(int max) create a stack of capacity max
void push(String item) add item to stack
String pop() return the string most recently pushed
boolean isEmpty() is the stack empty ?
int size() number of strings on the stack
Strawman API
Rationale. Allows us to represent the collection with an array of strings.
values
Strawman implementation: Instance variables and constructor
23
Data structure choice. Use an array to hold the collection.
instance variables
constructor
methods
test client
public class StrawStack
{
private String[] a;
private int N = 0;
public StrawStack(int max)
{ a = new String[max]; }
...
}
N
items on stack
a[0]
a[1]
a[2]
...
"upside down"
representation of
Strawman stack implementation: Test client
public static void main(String[] args)
{
int max = Integer.parseInt(args[0]);
StrawStack stack = new StrawStack(max);
while (!StdIn.isEmpty())
{
String item = StdIn.readString();
if (item.equals("-"))
StdOut.print(stack.pop());
else
stack.push(item);

}
StdOut.println();
}
24
What we expect, once the implementation is done.
instance variables
constructors
methods
test client
% more tobe.txt
to be or not to - be - - that - - - is
% java StrawStack 20 < tobe.txt
to be not that or be
Pop quiz 1 on stacks
Q. Can we always insert pop() commands to make items come out in sorted order?
25
Example 1. 6 5 4 3 2 1 - - - - - -
Example 2. 1 - 2 - 3 - 4 - 5 - 6 -
Example 3. 4 1 - 3 2 - - - 6 5 - -
4 4
1
4
3
4
3
2
4 4
3
4 6
5
6 6
1 2 3 4 5 6
Strawman implementation: Methods
public class StrawStack
{
...
public boolean isEmpty()
{ return (N == 0); }
public void push(String item)
{ a[N++] = item; }
public String pop()
{ return a[--N]; }
public int size()
{ return N; }
...
}
26
Methods define data-type operations (implement APIs).
instance variables
constructors
methods
test client
N
N
after
push()
N
after
pop()
all constant-time
one-liners!
Strawman pushdown stack implementation
public class StrawStack
{
private String[] a;
private int N = 0;
public StrawStack(int max)
{ a = new String[max]; }
public boolean isEmpty()
{ return (N == 0); }
public void push(String item)
{ a[N++] = item; }
public String pop()
{ return a[--N]; }
public int size()
{ return N; }
public static void main(String[] args)
{
int max = Integer.parseInt(args[0]);
StrawStack stack = new StrawStack(max);
while (!StdIn.isEmpty())
{
String item = StdIn.readString();
if (item.equals("-"))
StdOut.print(stack.pop() + " ");
else
stack.push(item);

}
StdOut.println();
}
}
27
instance variables
constructor
methods
test client
% more tobe.txt
to be or not to - be - - that - - - is
% java StrawStack 20 < tobe.txt
to be not that or be
Trace of strawman stack implementation (array representation)
28
push to be or not to - be - - that - - - is
pop to be not that or be
stack
contents
after
operation
a[0]
a[1]
a[2]
a[3]
a[4]
a[5]
a[6]
a[7]
a[8]
a[9]
a[10]
a[11]
a[12]
a[13]
a[14]
a[15]
a[16]
a[17]
a[18]
a[19]
to
be
to
N
to
be
or
to
be
or
not
to
be
or
not
to
to
be
or
not
to
to
be
or
not
be
to
be
or
not
be
to
be
or
not
be
to
be
or
that
be
to
be
or
that
be
to
be
or
that
be
to
be
or
that
be
to
is
or
that
be
Significant wasted space when stack size
is not near the capacity (typical).
• All operations are constant-time.
• Memory use is linear in the size of the collection,
when it is nonempty.
• No limits within the code on the collection size.
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
Benchmarking the strawman stack implementation
29
It does not implement the stack API or meet the performance specifications.
✘
✓
✘
StrawStack implements a fixed-capacity collection that behaves like a stack if the data fits.
Nice try, but need a new data structure.
✘
StrawStack requires client to provide capacity
Stack API
✘
StrawStack
works only
for strings
Performance
specifications
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.12.C.StacksQueues.Strawman
12. Stacks and Queues
•APIs
•Clients
•Strawman implementation
•Linked lists
•Implementations
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART II: ALGORITHMS, THEORY, AND MAC HINES
CS.12.D.StacksQueues.Lists
Data structures: sequential vs. linked
32
Sequential data structure
• Put objects next to one another.
• Machine: consecutive memory cells.
• Java: array of objects.
• Fixed size, arbitrary access.
Linked data structure
• Associate with each object a link to another one.
• Machine: link is memory address of next object.
• Java: link is reference to next object.
• Variable size, sequential access.
• Overlooked by novice programmers.
• Flexible, widely used method for organizing data.
i th element
next element
addr value
C0 "Alice"
C1 "Bob"
C2 "Carol"
C3
C4
C5
C6
C7
C8
C9
CA
CB
Array at C0
addr value
C0 "Carol"
C1 null
C2
C3
C4 "Alice"
C5 CA
C6
C7
C8
C9
CA "Bob"
CB C0
Linked list at C4
Simplest singly-linked data structure: linked list
33
Linked list
• A recursive data structure.
• Def. A linked list is null or a reference to a node.
• Def. A node is a data type that contains a reference to a node.
• 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.
private class Node
{
private String item;
private Node next;
}
"Alice" "Bob" "Carol"first
null
item next
A linked list
Singly-linked data structures
34
Even with just one link ( ) a wide variety of data structures are possible.
Multiply linked structures: many more possibilities!
From the point of view of a particular object,
all of these structures look the same.
Circular list (TSP)
Linked list (this lecture)
Rho
General case
Tree
Building a linked list
Node third = new Node();
third.item = "Carol";
third.next = null;
Node second = new Node();
second.item = "Bob";
second.next = third;
Node first = new Node();
first.item = "Alice";
first.next = second;
35
addr value
C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB"Bob"
second
"Alice"
first
third C0
first C4
second CA
"Carol"
third
null
"Carol"
null
"Bob"
C0
"Alice"
CA
List processing code
36
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.
List processing code: Remove and return the first item
37
item = first.item;
return item;
first = first.next;
Goal. Remove and return the first

item in a linked list first.
"Alice" "Bob" "Carol"first
"Alice" "Bob" "Carol"first"Alice"
item
first "Bob" "Carol""Alice"
item
first "Alice" "Bob" "Carol""Alice"
item
available for
garbage collection
List processing code: Add a new node at the beginning
38
Node second = first;
first.item = item;
first.next = second;
first = new Node();
Goal. Add item to a linked list first.
"Alice" "Bob" "Carol"first
second
first "Alice" "Bob" "Carol"
second
"Dave"
first "Alice" "Bob" "Carol"
second
"Alice" "Bob" "Carol"first
"Dave"
item
List processing code: Traverse a list
39
Goal. Visit every node on a linked list first.
"Alice" "Bob" "Carol"first
Node x = first;
while (x != null)
{
StdOut.println(x.item);
x = x.next;
}
x
Alice
Bob
Carol
StdOut
Pop quiz 1 on linked lists
Q. What is the effect of the following code (not-so-easy question)?
40
...
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);
...
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)?
42
...
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();
}
...
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.12.D.StacksQueues.Lists
14. Stacks and Queues
•APIs
•Clients
•Strawman implementation
•Linked lists
•Implementations
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART II: ALGORITHMS, THEORY, AND MAC HINES
CS.12.E.StacksQueues.Implementations
Pushdown stack implementation: Instance variables and constructor
45
Data structure choice. Use a linked list to hold the collection. instance variables
constructor
methods
test client
public class Stack<Item>
{
private Node first = null;

private int N = 0;
private class Node
{
private Item item;
private Node next;
}
...
}
objects on stack
first
use in place of concrete type
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]
Stack implementation: Test client
public static void main(String[] args)
{
Stack<String> stack = new Stack<String>();
while (!StdIn.isEmpty())
{
String item = StdIn.readString();
if (item.equals("-"))
System.out.print(stack.pop() + " ");
else
stack.push(item); 

}
StdOut.println();
}
46
What we expect, once the implementation is done.
instance variables
constructors
methods
test client
% more tobe.txt
to be or not to - be - - that - - - is
% java Stack < tobe.txt
to be not that or be
Stack implementation: Methods
public class Stack<Item>
{
...
public boolean isEmpty()
{ return first == null; }
public void push(Item item)
{
Node second = first;
first = new Node();
first.item = item;
first.next = second;
N++;
}
public Item pop()
{
Item item = first.item;
first = first.next;
N--;
return item;
}
public int size()
{ return N; }
...
}
47
Methods define data-type operations (implement the API).
instance variables
constructors
methods
test client
add a new node
to the beginning of the list
remove and return
first item on list
first
first
first
first
second
instance
variable
local variable
in push()
might also use N == 0
Stack implementation
public class Stack<Item>
{
private Node first = null;
private int N = 0;
private class Node
{
private Item item;
private Node next;
}
public boolean isEmpty()
{ return first == null; }
public void push(Item item)
{
Node second = first;
first = new Node();
first.item = item;
first.next = second;
N++;
}
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 }
}
48
instance variables
nested class
methods
test client
% more tobe.txt
to be or not to - be - - that - - - is
% java Stack < tobe.txt
to be not that or be
Trace of stack implementation (linked list representation)
49
push pop
to
be
or
not
to
- to
be
- be
- not
that
- that
- or
- be
is
be to
or be to
not or be to
to not or be to
be not or be to
that or be to
is to
to
Push to the
beginning
Pop from the
beginning
not or be to
not or be to
or be to
or be to
be to
to
• All operations are constant-time.
• Memory use is linear in the size of the collection,
when it is nonempty.
• No limits within the code on the collection size.
Performance
specifications
Benchmarking the stack implementation
50
It does implement the API and meet the performance specifications.
Stack implements the stack abstraction.
Made possible by linked data structure.
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
Stack API
✓
✓
✓
✓
Also possible to implement the queue abstraction with a singly-linked list (see text).
dequeue(): same code as pop()
enqueue(): slightly more complicated
Summary
51
Stacks and queues
• Fundamental collection abstractions.
• Differ only in order in which items are removed.
• Performance specifications: Constant-time for all
operations and space linear in the number of objects.
Linked structures
• Fundamental alternative to arrays.
• Enable implementations of the stack/queue abstractions
that meet performance specifications.
Next: Symbol tables
push to the
beginning
pop from the
beginning
Last
In
First
Out
enqueue at
the end
dequeue from
the beginning
First
In
First
Out
stack queue
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.12.E.StacksQueues.Implementations
http://introcs.cs.princeton.edu
R O B E R T S E D G E W I C K
K E V I N W A Y N E
ComputerScience
Computer
ScienceAn Interdisciplinary Approach
12. Stacks and Queues
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART II: ALGORITHMS, THEORY, AND MAC HINES
Section 4.3

More Related Content

PDF
Functional Programming Patterns for the Pragmatic Programmer
PPTX
PDF
Stacks
PPT
Templates exception handling
PPTX
Templates presentation
PDF
Generic programming and concepts that should be in C++
PDF
Generic Programming
PPT
Scala functions
Functional Programming Patterns for the Pragmatic Programmer
Stacks
Templates exception handling
Templates presentation
Generic programming and concepts that should be in C++
Generic Programming
Scala functions

What's hot (20)

PDF
O caml2014 leroy-slides
PDF
Fun with Lambdas: C++14 Style (part 1)
PDF
Implicit conversion and parameters
PPTX
ScalaDays 2013 Keynote Speech by Martin Odersky
PPT
2CPP15 - Templates
ODP
Functional Programming With Scala
PPT
Templates
PPTX
Programming in java - Concepts- Operators- Control statements-Expressions
PDF
Hey! There's OCaml in my Rust!
KEY
Exciting JavaScript - Part I
PDF
Java Script Workshop
ODP
Functors, Applicatives and Monads In Scala
PDF
Scala categorytheory
PDF
Introduction to functional programming using Ocaml
PDF
Functional programming in kotlin with Arrow [Sunnytech 2018]
PDF
CallSharp: Automatic Input/Output Matching in .NET
PDF
A taste of Functional Programming
PPTX
Type Casting Operator
PDF
Python Programming - IX. On Randomness
ODP
Clojure basics
O caml2014 leroy-slides
Fun with Lambdas: C++14 Style (part 1)
Implicit conversion and parameters
ScalaDays 2013 Keynote Speech by Martin Odersky
2CPP15 - Templates
Functional Programming With Scala
Templates
Programming in java - Concepts- Operators- Control statements-Expressions
Hey! There's OCaml in my Rust!
Exciting JavaScript - Part I
Java Script Workshop
Functors, Applicatives and Monads In Scala
Scala categorytheory
Introduction to functional programming using Ocaml
Functional programming in kotlin with Arrow [Sunnytech 2018]
CallSharp: Automatic Input/Output Matching in .NET
A taste of Functional Programming
Type Casting Operator
Python Programming - IX. On Randomness
Clojure basics
Ad

Similar to stacks and queues class 12 in c++ (20)

PPT
05-stack_queue.ppt
PPT
Stack linked list
PPTX
stacks and queues for public
PDF
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
PPTX
My lecture stack_queue_operation
PDF
02 stackqueue
PPT
stack.ppt
PPT
16-StacksQueuesCVCJUCGTCXYFRSTTIUGIUFTY.ppt
PPTX
13 Stacks and Queues.pptx
PDF
Lesson 4 stacks and queues
PPTX
Stack & Queue
PDF
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
PPT
Queue Data Structure
PPT
Queue Data Structure
PPT
2 b queues
DOCX
Files to submitProperQueue.javaCreate this file and implement .docx
PPTX
stack & queue
PPT
stack and queue array implementation, java.
PPT
stack and queue array implementation in java.
PPTX
U3.stack queue
05-stack_queue.ppt
Stack linked list
stacks and queues for public
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
My lecture stack_queue_operation
02 stackqueue
stack.ppt
16-StacksQueuesCVCJUCGTCXYFRSTTIUGIUFTY.ppt
13 Stacks and Queues.pptx
Lesson 4 stacks and queues
Stack & Queue
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
Queue Data Structure
Queue Data Structure
2 b queues
Files to submitProperQueue.javaCreate this file and implement .docx
stack & queue
stack and queue array implementation, java.
stack and queue array implementation in java.
U3.stack queue
Ad

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Approach and Philosophy of On baking technology
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
Teaching material agriculture food technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Empathic Computing: Creating Shared Understanding
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Unlocking AI with Model Context Protocol (MCP)
Building Integrated photovoltaic BIPV_UPV.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Spectroscopy.pptx food analysis technology
Understanding_Digital_Forensics_Presentation.pptx
Network Security Unit 5.pdf for BCA BBA.
Reach Out and Touch Someone: Haptics and Empathic Computing
Approach and Philosophy of On baking technology
Advanced methodologies resolving dimensionality complications for autism neur...
Teaching material agriculture food technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
MYSQL Presentation for SQL database connectivity
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Spectral efficient network and resource selection model in 5G networks
Empathic Computing: Creating Shared Understanding
NewMind AI Weekly Chronicles - August'25 Week I
Dropbox Q2 2025 Financial Results & Investor Presentation
Unlocking AI with Model Context Protocol (MCP)

stacks and queues class 12 in c++

  • 1. http://introcs.cs.princeton.edu R O B E R T S E D G E W I C K K E V I N W A Y N E ComputerScience Computer ScienceAn Interdisciplinary Approach 12. Stacks and Queues C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART II: ALGORITHMS, THEORY, AND MAC HINES Section 4.3 12. Stacks and Queues •APIs •Clients •Strawman implementation •Linked lists •Implementations C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART II: ALGORITHMS, THEORY, AND MAC HINES CS.12.A.StacksQueues.APIs Data types and data structures 3 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? Stack and Queue APIs 4 Stack operations • Add an item to the collection. • Remove and return the item most recently added (LIFO). • Test if the collection is empty. • Return the size of the collection. Two fundamental collection ADTs differ in just a detail of the specification of their operations. A collection is an ADT whose values are a multiset of items, all of the same type. Queue operations • Add an item to the collection. • Remove and return the item least recently added (FIFO). • Test if the collection is empty. • Return the size of the collection. Stacks and queues both arise naturally in countless applications. A key characteristic. No limit on the size of the collection. Add to the beginning Add to the end Take from the beginning Last In First Out Take from the beginning First In First Out
  • 2. Example of stack operations 5 Push. Add an item to the collection. Pop. Remove and return the item most recently added. push to be or not to - be - - that - - - is pop stack contents after operation push to the top pop from the top Last In First Out to be to or be to not or be to to not or be to push to the top be not or be to that or be to is to pop from
 the top to not or be to be not or be to not or be to that or be to or be to be to Example of queue operations 6 Enqueue. Add an item to the collection. Dequeue. Remove and return the item least recently added. to to be to be or to be or not to be or not to be or not to be not to be that that is enqueue to be or not to - be - - that - - - is dequeue queue contents after operation enqueue at the end dequeue from the beginning First In First Out enqueue at the end dequeue from the beginning to be or not to be or not to be or not to be not to be that to be that be that Java approach: Parameterized data types (generics) • Use placeholder type name in definition. • Substitute concrete type for placeholder in clients. Parameterized data types 7 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 objects on the stack Stack API public class Queue<Item> Queue<Item>() create a queue of items, all of type Item void enqueue(Item item) add item to queue Item dequeue() remove and return the item least recently enqueued boolean isEmpty() is the queue empty ? int size() # of objects on the queue Queue API Goal. Simple, safe, and clear client code for collections of any type of data. stay tuned for examples Performance specifications 8 • All operations are constant-time. • Memory use is linear in the size of the 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. Goal. Simple, safe, clear, and efficient client code. Challenge. Provide guarantees on performance. Performance specifications Typically required for client code to be scalable
  • 3. C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.12.A.StacksQueues.APIs 12. Stacks and Queues •APIs •Clients •Strawman implementation •Linked lists •Implementations C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART II: ALGORITHMS, THEORY, AND MAC HINES CS.12.B.StacksQueues.Clients Stack and queue applications 11 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. Queue client example: Read all strings from StdIn into an array public class QEx { public static String[] readAllStrings() { /* See next slide. */ } public static void main(String[] args) { String[] words = readAllStrings(); for (int i = 0; i < words.length; i++) StdOut.println(words[i]); } } 12 Challenge • Can’t store strings in array before creating the array. • Can’t create the array without knowing how many strings are in the input stream. • Can’t know how many strings are in the input stream without reading them all. Solution: Use a Queue<String>. % more moby.txt moby dick herman melville call me ishmael some years ago never mind how long precisely having little or no money ... % java QEx < moby.txt moby dick herman melville call me ishmael some years ... Note: StdIn has this functionality
  • 4. Queue client example: Read all strings from StdIn into an array public class QEx { public static String[] readAllStrings() { Queue<String> q = new Queue<String>(); while (!StdIn.isEmpty()) q.enqueue(StdIn.readString()); int N = q.size(); String[] words = new String[N]; 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 Solution: Use a Queue<String>. • Store strings in the queue. • Get the size when all have been read from StdIn. • Create an array of that size. • Copy the strings into the array. Stack example: "Back" button in a browser 14 http://introcs.cs.princeton.edu/java/home/ http://introcs.cs.princeton.edu/java/40algorithms/ http://introcs.cs.princeton.edu/java/43stack/ 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. Autoboxing 15 Wrapper types • Each primitive type has a wrapper reference type. • Wrapper type has larger set of operations than primitive type.
 Example: Integer.parseInt(). • Instances of wrapper types are objects. • Wrapper type can be used in a parameterized ADT. Autoboxing. Automatic cast from primitive type to wrapper type. Challenge. Use a primitive type in a parameterized ADT. primitive type wrapper type int Integer char Character double Double boolean Boolean Auto-unboxing. Automatic cast from wrapper type to primitive type. Simple client code (no casts) Stack<Integer> stack = new Stack<Integer>(); stack.push(17); // Autobox (int -> Integer) int a = stack.pop(); // Auto-unbox (Integer -> int) Stack client example: Postfix expression evaluation 16 Example. 1 2 3 + 4 5 * * + 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). There is only one way to parenthesize a postfix expression. Next. With a stack, postfix expressions are easy to evaluate. 1 ( 2 + 3 ) 4 5 * * + 1 2 3 + 4 5 * * + Remarkable fact. No parentheses are needed! find first operator, convert to infix, enclose in () 1 ( ( 2 + 3 ) * ( 4 * 5 ) ) + iterate, treating subexpressions in parentheses as atomic ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) also called "reverse Polish" notation (RPN) Jan ukasiewicz 1878⇥1956 HP-35 (1972)
 First handheld calculator. "Enter" means "push". No parentheses. Made slide rules obsolete (!)
  • 5. = = + Postfix arithmetic expression evaluation 17 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 * * 5= 20= 100 101 1 2 3 + 4 5 * * + 1 1011 2 1 2 3 1 5 1 5 4 1 5 4 5 1 5 20 1 100 Stack client example: Postfix expression evaluation public class Postfix { public static void main(String[] args) { Stack<Double> stack = new Stack<Double>(); while (!StdIn.isEmpty()) { String token = StdIn.readString(); 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(-stack.pop() + stack.pop()); else if (token.equals("/")) stack.push((1.0/stack.pop()) * stack.pop()); else if (token.equals("sqrt")) stack.push(Math.sqrt(stack.pop())); else stack.push(Double.parseDouble(token)); } StdOut.println(stack.pop()); } } 18 % java Postfix 1 2 3 + 4 5 * * + 101.0 % java Postfix 1 5 sqrt + 2 / 1.618033988749895 + Perspective • Easy to add operators of all sorts. • Can do infix with two stacks (see text). • Could output machine language code. • Indicative of how Java compiler works. 100 100 moveto 100 300 lineto 300 300 lineto 300 100 lineto stroke Real-world stack application: PostScript 19 PostScript (Warnock-Geschke, 1980s): A turtle with a stack. • Postfix program code (push literals; functions pop arguments). • Add commands to drive virtual graphics machine. • Add loops, conditionals, functions, types, fonts, strings.... A simple virtual machine, but not a toy • Easy to specify published page. • Easy to implement on various specific printers. • Revolutionized world of publishing. 100 300 Another stack machine: The JVM (Java Virtual Machine)! push(100) PostScript code define a path draw the path call "moveto" (takes args from stack) C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.12.A.StacksQueues.APIsCS.12.B.StacksQueues.Clients 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
  • 6. 12. Stacks and Queues •APIs •Clients •Strawman implementation •Linked lists •Implementations C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART II: ALGORITHMS, THEORY, AND MAC HINES CS.12.C.StacksQueues.Strawman Warmup: simplify the ADT • Implement only for items of type String. • Have client provide a stack capacity in the constructor. Strawman ADT for pushdown stacks 22 public class StrawStack StrawStack(int max) create a stack of capacity max void push(String item) add item to stack String pop() return the string most recently pushed boolean isEmpty() is the stack empty ? int size() number of strings on the stack Strawman API Rationale. Allows us to represent the collection with an array of strings. values Strawman implementation: Instance variables and constructor 23 Data structure choice. Use an array to hold the collection. instance variables constructor methods test client public class StrawStack { private String[] a; private int N = 0; public StrawStack(int max) { a = new String[max]; } ... } N items on stack a[0] a[1] a[2] ... "upside down" representation of Strawman stack implementation: Test client public static void main(String[] args) { int max = Integer.parseInt(args[0]); StrawStack stack = new StrawStack(max); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (item.equals("-")) StdOut.print(stack.pop()); else stack.push(item);
 } StdOut.println(); } 24 What we expect, once the implementation is done. instance variables constructors methods test client % more tobe.txt to be or not to - be - - that - - - is % java StrawStack 20 < tobe.txt to be not that or be
  • 7. Pop quiz 1 on stacks Q. Can we always insert pop() commands to make items come out in sorted order? 25 Example 1. 6 5 4 3 2 1 - - - - - - Example 2. 1 - 2 - 3 - 4 - 5 - 6 - Example 3. 4 1 - 3 2 - - - 6 5 - - 4 4 1 4 3 4 3 2 4 4 3 4 6 5 6 6 1 2 3 4 5 6 Strawman implementation: Methods public class StrawStack { ... public boolean isEmpty() { return (N == 0); } public void push(String item) { a[N++] = item; } public String pop() { return a[--N]; } public int size() { return N; } ... } 26 Methods define data-type operations (implement APIs). instance variables constructors methods test client N N after push() N after pop() all constant-time one-liners! Strawman pushdown stack implementation public class StrawStack { private String[] a; private int N = 0; public StrawStack(int max) { a = new String[max]; } public boolean isEmpty() { return (N == 0); } public void push(String item) { a[N++] = item; } public String pop() { return a[--N]; } public int size() { return N; } public static void main(String[] args) { int max = Integer.parseInt(args[0]); StrawStack stack = new StrawStack(max); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (item.equals("-")) StdOut.print(stack.pop() + " "); else stack.push(item);
 } StdOut.println(); } } 27 instance variables constructor methods test client % more tobe.txt to be or not to - be - - that - - - is % java StrawStack 20 < tobe.txt to be not that or be Trace of strawman stack implementation (array representation) 28 push to be or not to - be - - that - - - is pop to be not that or be stack contents after operation a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] a[12] a[13] a[14] a[15] a[16] a[17] a[18] a[19] to be to N to be or to be or not to be or not to to be or not to to be or not be to be or not be to be or not be to be or that be to be or that be to be or that be to be or that be to is or that be Significant wasted space when stack size is not near the capacity (typical).
  • 8. • All operations are constant-time. • Memory use is linear in the size of the collection, when it is nonempty. • No limits within the code on the collection size. 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 Benchmarking the strawman stack implementation 29 It does not implement the stack API or meet the performance specifications. ✘ ✓ ✘ StrawStack implements a fixed-capacity collection that behaves like a stack if the data fits. Nice try, but need a new data structure. ✘ StrawStack requires client to provide capacity Stack API ✘ StrawStack works only for strings Performance specifications C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.12.C.StacksQueues.Strawman 12. Stacks and Queues •APIs •Clients •Strawman implementation •Linked lists •Implementations C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART II: ALGORITHMS, THEORY, AND MAC HINES CS.12.D.StacksQueues.Lists Data structures: sequential vs. linked 32 Sequential data structure • Put objects next to one another. • Machine: consecutive memory cells. • Java: array of objects. • Fixed size, arbitrary access. Linked data structure • Associate with each object a link to another one. • Machine: link is memory address of next object. • Java: link is reference to next object. • Variable size, sequential access. • Overlooked by novice programmers. • Flexible, widely used method for organizing data. i th element next element addr value C0 "Alice" C1 "Bob" C2 "Carol" C3 C4 C5 C6 C7 C8 C9 CA CB Array at C0 addr value C0 "Carol" C1 null C2 C3 C4 "Alice" C5 CA C6 C7 C8 C9 CA "Bob" CB C0 Linked list at C4
  • 9. Simplest singly-linked data structure: linked list 33 Linked list • A recursive data structure. • Def. A linked list is null or a reference to a node. • Def. A node is a data type that contains a reference to a node. • 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. private class Node { private String item; private Node next; } "Alice" "Bob" "Carol"first null item next A linked list Singly-linked data structures 34 Even with just one link ( ) a wide variety of data structures are possible. Multiply linked structures: many more possibilities! From the point of view of a particular object, all of these structures look the same. Circular list (TSP) Linked list (this lecture) Rho General case Tree Building a linked list Node third = new Node(); third.item = "Carol"; third.next = null; Node second = new Node(); second.item = "Bob"; second.next = third; Node first = new Node(); first.item = "Alice"; first.next = second; 35 addr value C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB"Bob" second "Alice" first third C0 first C4 second CA "Carol" third null "Carol" null "Bob" C0 "Alice" CA List processing code 36 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.
  • 10. List processing code: Remove and return the first item 37 item = first.item; return item; first = first.next; Goal. Remove and return the first
 item in a linked list first. "Alice" "Bob" "Carol"first "Alice" "Bob" "Carol"first"Alice" item first "Bob" "Carol""Alice" item first "Alice" "Bob" "Carol""Alice" item available for garbage collection List processing code: Add a new node at the beginning 38 Node second = first; first.item = item; first.next = second; first = new Node(); Goal. Add item to a linked list first. "Alice" "Bob" "Carol"first second first "Alice" "Bob" "Carol" second "Dave" first "Alice" "Bob" "Carol" second "Alice" "Bob" "Carol"first "Dave" item List processing code: Traverse a list 39 Goal. Visit every node on a linked list first. "Alice" "Bob" "Carol"first Node x = first; while (x != null) { StdOut.println(x.item); x = x.next; } x Alice Bob Carol StdOut Pop quiz 1 on linked lists Q. What is the effect of the following code (not-so-easy question)? 40 ... 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); ...
  • 11. 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)? 42 ... 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(); } ... C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.12.D.StacksQueues.Lists 14. Stacks and Queues •APIs •Clients •Strawman implementation •Linked lists •Implementations C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART II: ALGORITHMS, THEORY, AND MAC HINES CS.12.E.StacksQueues.Implementations
  • 12. Pushdown stack implementation: Instance variables and constructor 45 Data structure choice. Use a linked list to hold the collection. instance variables constructor methods test client public class Stack<Item> { private Node first = null;
 private int N = 0; private class Node { private Item item; private Node next; } ... } objects on stack first use in place of concrete type 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] Stack implementation: Test client public static void main(String[] args) { Stack<String> stack = new Stack<String>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (item.equals("-")) System.out.print(stack.pop() + " "); else stack.push(item); 
 } StdOut.println(); } 46 What we expect, once the implementation is done. instance variables constructors methods test client % more tobe.txt to be or not to - be - - that - - - is % java Stack < tobe.txt to be not that or be Stack implementation: Methods public class Stack<Item> { ... public boolean isEmpty() { return first == null; } public void push(Item item) { Node second = first; first = new Node(); first.item = item; first.next = second; N++; } public Item pop() { Item item = first.item; first = first.next; N--; return item; } public int size() { return N; } ... } 47 Methods define data-type operations (implement the API). instance variables constructors methods test client add a new node to the beginning of the list remove and return first item on list first first first first second instance variable local variable in push() might also use N == 0 Stack implementation public class Stack<Item> { private Node first = null; private int N = 0; private class Node { private Item item; private Node next; } public boolean isEmpty() { return first == null; } public void push(Item item) { Node second = first; first = new Node(); first.item = item; first.next = second; N++; } 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 } } 48 instance variables nested class methods test client % more tobe.txt to be or not to - be - - that - - - is % java Stack < tobe.txt to be not that or be
  • 13. Trace of stack implementation (linked list representation) 49 push pop to be or not to - to be - be - not that - that - or - be is be to or be to not or be to to not or be to be not or be to that or be to is to to Push to the beginning Pop from the beginning not or be to not or be to or be to or be to be to to • All operations are constant-time. • Memory use is linear in the size of the collection, when it is nonempty. • No limits within the code on the collection size. Performance specifications Benchmarking the stack implementation 50 It does implement the API and meet the performance specifications. Stack implements the stack abstraction. Made possible by linked data structure. 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 Stack API ✓ ✓ ✓ ✓ Also possible to implement the queue abstraction with a singly-linked list (see text). dequeue(): same code as pop() enqueue(): slightly more complicated Summary 51 Stacks and queues • Fundamental collection abstractions. • Differ only in order in which items are removed. • Performance specifications: Constant-time for all operations and space linear in the number of objects. Linked structures • Fundamental alternative to arrays. • Enable implementations of the stack/queue abstractions that meet performance specifications. Next: Symbol tables push to the beginning pop from the beginning Last In First Out enqueue at the end dequeue from the beginning First In First Out stack queue C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.12.E.StacksQueues.Implementations
  • 14. http://introcs.cs.princeton.edu R O B E R T S E D G E W I C K K E V I N W A Y N E ComputerScience Computer ScienceAn Interdisciplinary Approach 12. Stacks and Queues C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART II: ALGORITHMS, THEORY, AND MAC HINES Section 4.3