Download Ch22 - Skylight Publishing

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Methods
Object-Oriented Programming
and Data Structures
2nd AP edition  with GridWorld
Maria Litvin ● Gary Litvin
P
T
E
R
A
H
C
2 2
Stacks and Queues
Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
Objectives:
• Discuss different implementations of stacks
and queues
• Learn about applications of stacks and
queues
22-2
Stack
Queue
pop
push
remove
add
LIFO (Last-In-First-Out)
access method
FIFO (First-In-First-Out)
access method
Stacks and queues are used for temporary
storage, but in different situations
22-3
Stacks are Used for
• handling nested structures:


processing directories within directories
evaluating expressions within expressions
• handling branching processes:



traversing a branching tree structure
planning a move in a chess game
tracking the sequence of method calls in a Java
program
22-4
Stack: Array
Implementation
myElements[5]
myElements[4]
myElements[3]
myElements[2]
myElements[1]
myElements[0]
Stack
pointer
value3
value2
value1
value0
sp
public void push (Object x)
{
myElements [sp] = x;
sp++;
}
public Object pop ( )
{
sp--;
return myElements [sp];
}
22-5
ArrayList Implementation
import java.util.ArrayList;
public class ArrayStack
{
private ArrayList<Object> items;
public ArrayStack ( )
{ items = new ArrayList<Object>( ); }
public boolean isEmpty ( ) { return items.isEmpty ( ); }
public void push (Object x) { items.add (x); }
public Object pop ( )
{ return items.remove (items.size ( ) - 1); }
public Object peek ( )
{ return items.get (items.size ( ) - 1); }
}
22-6
LinkedList Implementation
import java.util.LinkedList;
public class ListStack
{
private LinkedList<Object> items;
public ListStack ()
{ items = new LinkedList<Object> ( ); }
public boolean isEmpty ( ) { return items.isEmpty ( ); }
public void push (Object x) { items.addFirst (x); }
public Object pop ( ) { return items.removeFirst ( ); }
public Object peek ( ) { return items.getFirst ( ); }
}
22-7
Properties of Stacks
• In an efficient implementation, push, pop, and
peek methods run in O(1) time.
• A stack of objects holds references to objects.
• If necessary, a stack can hold multiple
references to the same object.
• If you are not careful, an object can change
while stored on the stack (unless that object
is immutable).
22-8
java.util.Stack class
• Part of the Java Collections Framework
(Chapter 20).
• A “generic” class (works with objects of
specified type).
• Based on the legacy Vector class, similar to
ArrayList.
• Methods: isEmpty, push, pop, peek.
• Has other methods  do not use them!
22-9
Stack Example: Matching Brackets
public boolean bracketsMatch (String str) import java.util.Stack;
{
Stack<Integer> stk = new Stack<Integer> ( );
for (int pos = 0; pos < str.length( ); pos++)
{
if (str.charAt (pos) == ' [ ' ) )
stk.push (pos);
Autoboxing
else if (str.charAt (pos) == ' ] ' ))
(Save pos of ' [ ‘)
{
if (stk.isEmpty ( ))
return false;
Autounboxing
int pos0 = stk.pop ( );
System.out.println (pos0 + " - " + pos);
}
}
return stk.isEmpty ( );
}
22-10
Stack Example:
Traversing
a Tree
Stack stk = new Stack<TreeNode>( );
TreeNode node = root;
while (node != null)
{
System.out.println (node.getValue ( ));
if (node.getLeft ( ) != null )
{
if (node.getRight ( ) != null )
stk.push (node.getRight ( ));
Save for future
node = node.getLeft ( );
processing
}
else if (node.getRight ( ) != null )
node = node.getRight ( );
else if (! stk.isEmpty ( ))
node = stk.pop ( );
if no children,
else
take the next
node = null;
node from the
}
stack
22-11
Queues are used for:
• Processing events or messages in order of
their arrival
• System tasks



Queueing print jobs
Entering keystrokes
Processing mouse clicks
22-12
Queue: Ring-Buffer
Implementation
Before:
front
1
rear
1
2
3
5
8
13
3
5
8
13
After:
(removed 1, 1; inserted 21, 34, 55)
rear
55
front
2
21
34
22-13
Properties of Queues
• In an efficient implementation, add, remove,
and peek methods run in O(1) time.
• A queue of objects holds references to
objects.
• If necessary, a queue can hold multiple
references to the same object.
• If you are not careful, an object can change
while stored in the queue (unless that object
is immutable).
22-14
The java.util.Queue Interface
boolean isEmpty ()
boolean add (E obj)
E remove ()
E peek ()
• A “generic” interface, part of the Java
Collections Framework (Chapter 20)
• Implemented by java.util.LinkedList
22-15
Queue Example
public Queue<String> findMatches (Scanner input,
String target)
{
Queue<String> q = new LinkedList<String>( );
while (input.hasNextLine ( ))
{
Returns a queue of
String line = input.nextLine ( );
all the lines that
if (line.indexOf (target) >= 0 )
contain target
q.add (line);
}
public void process (Queue<String> q)
return q;
{
}
while (! q.isEmpty ( ))
{
Processes the
String s = q.remove ( );
contents of q
... // process s
(leaves the
}
queue empty)
}
22-16
Review:
• What are the two main operations for a
stack?
• Name a few applications of stacks.
• Name the four methods of the java.util.Stack
class.
• What are the two main operations for a
queue?
• Name a few applications of queues.
22-17
Review (cont’d):
• Name the four methods of the java.util.Queue
interface.
• Explain why a stack of objects can be equally
efficiently implemented using an ArrayList or
a LinkedList.
• Why is an ArrayList not as efficient for
implementing a queue (unless you use a
ring-buffer implementation)?
22-18