Chapter 22 - Stacks and queues. After you have mastered the material in this chapter, you will be able to: Discuss different implementations of stacks and queues, learn about applications of stacks and queues.
Trang 1Stacks and Queues
C H
A P
T E
R 2 2
Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing All
rights reserved.
Java Methods
Object-Oriented Programming
and Data Structures
Maria Litvin ● Gary Litvin
2nd AP edition with GridWorld
Trang 2Objectives:
• Discuss different implementations of stacks and queues
• Learn about applications of stacks and
queues
Trang 3push pop
LIFO (Last-In-First-Out)
access method
add remove
FIFO (First-In-First-Out) access method
Stacks and queues are used for temporary
storage, but in different situations
Trang 4Stacks 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
Trang 5Stack: Array
Implementation
Stack pointer
sp
myElements[5]
myElements[4]
myElements[3] value3
myElements[2] value2
myElements[1] value1
myElements[0] value0
public void push (Object x) {
myElements [sp] = x; sp++;
}
public Object pop ( ) {
sp ;
return myElements [sp]; }
Trang 6import 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); }
}
Trang 7import 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 ( ); }
}
Trang 8Properties 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).
Trang 9• 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!
Trang 10Stack Example: Matching Brackets
public boolean bracketsMatch (String str)
{
Stack<Integer> stk = new Stack<Integer> ( );
for (int pos = 0; pos < str.length( ); pos++)
{
if (str.charAt (pos) == ' [ ' ) )
stk.push (pos);
else if (str.charAt (pos) == ' ] ' ))
{
if (stk.isEmpty ( ))
return false;
int pos0 = stk.pop ( );
System.out.println (pos0 + " - " + pos);
}
}
return stk.isEmpty ( );
}
Autounboxing
Autoboxing (Save pos of ' [ ‘) import java.util.Stack;
Trang 11Stack 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 ( )); node = node.getLeft ( );
}
else if (node.getRight ( ) != null ) node = node.getRight ( );
else if (! stk.isEmpty ( )) node = stk.pop ( );
else node = null;
}
Save for future processing
if no children, take the next node from the stack
Trang 12Queues are used for:
• Processing events or messages in order of their arrival
• System tasks
Queueing print jobs
Entering keystrokes
Processing mouse clicks
Trang 13Queue: Ring-Buffer
Implementation
1 1 2 3 5 8 13
Before:
After:
(removed 1, 1; inserted 21, 34, 55)
2 3 5 8 13 21 34
55
Trang 14Properties 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).
Trang 15• A “generic” interface, part of the Java
Collections Framework (Chapter 20)
• Implemented by java.util.LinkedList
boolean isEmpty () boolean add (E obj)
E remove ()
E peek ()
Trang 16Queue Example
public Queue<String> findMatches (Scanner input,
String target)
{
Queue<String> q = new LinkedList<String>( );
while (input.hasNextLine ( ))
{
String line = input.nextLine ( );
if (line.indexOf (target) >= 0 )
q.add (line);
}
return q;
}
Returns a queue of all the lines that
contain target
public void process (Queue<String> q) {
while (! q.isEmpty ( ))
{
String s = q.remove ( );
// process s
}
}
Processes the
contents of q
(leaves the
queue empty)
Trang 17Review:
• 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.
Trang 18Review (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)?