Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Methods Stacks and Queues A & AB Object-Oriented Programming

Similar presentations


Presentation on theme: "Java Methods Stacks and Queues A & AB Object-Oriented Programming"— Presentation transcript:

1 Java Methods Stacks and Queues A & AB Object-Oriented Programming
and Data Structures Maria Litvin ● Gary Litvin This chapter also contains a case study on asynchronous computing architectures (Actors). Stacks and Queues Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

2 Objectives: Discuss different implementations of stacks and queues
Learn about applications of stacks and queues These two data structures are in contract with each other.

3 Stack Queue pop remove push add LIFO (Last-In-First-Out) access method FIFO (First-In-First-Out) access method The queue operations are sometimes called enqueue and dequeue, but Java uses add and remove. Stacks and queues are used for temporary storage, but in different situations

4 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 Often recursion is a more straightforward way of handling such tasks. Recursive method calls use the system stack behind the scenes.

5 Stack: Array Implementation
public void push (Object x) { myElements [sp] = x; sp++; } public Object pop ( ) sp--; return myElements [sp]; In this implementation, the stack pointer points to the next available slot. In another implementation it might point to the top value.

6 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); } } A simple and efficient implementation.

7 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 (); } } As simple and as efficient as the ArrayList implementation.

8 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). Storing an object on stack in itself does not protect it from further changes.

9 java.util.Stack class Part of the Java Collections Framework (Chapter 19). 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! java.util.Stack extends java.util.Vector.

10 Stack Example: Matching Brackets
import java.util.Stack; 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 (); Autoboxing (Save pos of ' [ ‘) If brackets match, the stack must be empty at the end. Autounboxing

11 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 ()); 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 Tree traversal is much easier with recursion (Chapter 23). if no children, take the next node from the stack

12 Queues are used for: Processing events or messages in order of their arrival System tasks Queueing print jobs Entering keystrokes Processing mouse clicks Queues can be also used in sorting.

13 Queue: Ring-Buffer Implementation
In a personal computer, a small ring buffer is used for queuing characters typed on the keyboard.

14 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). Storing an object in a queue in itself does not protect it from further changes.

15 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 19) Implemented by java.util.LinkedList Thus the Java Collections Framework does not have a special class for queues: it uses LinkedList. Remember: java.util.Stack is a class but java.util.Queue is an interface.

16 Queue 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 } Here the lines of text read from input are processed in the same order. Processes the contents of q (leaves the queue empty)

17 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. What are the two main operations for a stack? push and pop. Name a few applications of stacks. Processing all files in nested directories; evaluation of nested expressions; traversing a tree. Name the four methods of the java.util.Stack class. isEmpty, push, pop, peek. What are the two main operations for a queue? add and remove. Name a few applications of queues. Processing events; system tasks, such as queuing print jobs.

18 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)? Name the four methods of the java.util.Queue interface. isEmpty, add, remove, peek. Explain why a stack of objects can be equally efficiently implemented using an ArrayList or a LinkedList. Adding and removing a value at the end of the list is equally efficient: takes O(1) time. Why is an ArrayList not as efficient for implementing a queue (unless you use a ring-buffer implementation)? Removing (or adding) a value at the beginning of an array takes O(n) time.


Download ppt "Java Methods Stacks and Queues A & AB Object-Oriented Programming"

Similar presentations


Ads by Google