Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Stacks and Queues Starring: IndexOutOfBOundsException Co-Starring: NoSuchElementException 1 Purpose: In this lecture series we will discuss two more ADTs The Stack and Queue data types are used to process data in a linear fashion 2 Resources: Barrons Chapter 9 p.300 (EXCEPT Priority Queues p.305-309) Fundamentals of Java Chapter 15 p.583 Java Essentials Chapter 19 p.757 Java Essentials Study Guide Chapter 16 p.281 Java Methods Chapter 3 p.61 3 Handouts: 1. Stack and Queue Interfaces & Implementations 2.The Following Java Code/API: Stack API (class) Queue API (interface) ArrayStack.java ListQueue.java 4 Intro: A STACK is a linearly ordered list A STACK is a data structure used for storing and retrieving data elements in such a way that the element stored last will be retrieved first. LIFO --- last in first out 5 Intro: A QUEUE is a data structure used for temporary storage from which the data elements are retrieved in the same order as they were stored. FIFO – first in first out Used for processing events that have to be processed in the order of their arrival (events are buffered in the queue) 6 Stacks: Think of the mountain of clothes piled in a corner of your room As you hurry to dress so as not to be late for school, you begin your search from the TOP of the clothes pile The last stuff to be thrown on to the pile is the first to be examined This is a “messy” stack 7 TO implement a Stack ADT, you must provide a way to store (push) and remove (pop) elements from a Stack Elements on the stack should be of the same type (or in the same class hierarchy) A Stack has no limits as to its size 8 TO add an element on to the stack you “Push” that item and it goes to the front of the stack TO remove an element from the stack, you can only “Pop” off the element currently at the top of the stack PUSH --- adds elements to the top of the stack POP --- removes the element from the top of the stack 9 The PUSH and POP operations should be in Constant time O(1) PEEK --- return the top element of the Stack without removing it EMPTY --- see if the Stack has any elements left in it SEARCH --- returns the position where an object is on the Stack 10 For testing purposes, we will use the Java Stack Class (the actual Java class is posted on the website and provided as a handout) 11 public class Stack<E> extends Vector<E> { public Stack() { } public E push(E item) { addElement(item); return item; } public synchronized E pop() { E obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj; } public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } 12 public boolean empty() { return size() == 0; } public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; } 13 RUNTIME STACK Remember the “runtime stack” ? It uses stacks to handle function calls The stack holds the function specific data PLUS the memory address of the NEXT instruction to execute Elements are “on the stack” 14 The stack is controlled by the two main operations: PUSH & POP Lets look at an example of how we can use the Stack Class, YOU are required to understand the BIG-O of each method and the use of Generics in the Stack class. After we examine the Stack class, we will write our own implementation of the Stack class. 15 Stack<Integer> sI = new Stack<Integer>(); sI.push(21); sI.push(42); sI.push(84); for(Integer i:sI) { System.out.println(i.toString()); } sI.pop(); System.out.println(sI.peek().toString()); System.out.println(sI.empty()); System.out.println(sI.search(21)); 16 You could Implement a Stack as a singly linked list enhanced by an additional reference to the tail of the list Elements are added at the tail of the list and removed at the head of the list. However, lets look at an ArrayList Implementation 17 public class arrayStack <E> extends Stack<E>{ private ArrayList<E> array; public arrayStack() //(E i) { // value = i; array = new ArrayList<E>(); } public E push(E item) { array.add (item); return item; } public E pop() { return array.remove(array.size() - 1); } 18 public E peek() { return array.get(array.size() - 1); } public boolean empty() { return array.size() == 0; } public int search(Object o) { int i = array.lastIndexOf(o); if (i >= 0) { return array.size() - i; } return -1; } } 19 To use the Stack: // SPVM arrayStack<String> mS = new arrayStack<String>(); mS.push("Billy"); mS.push("Joe"); mS.push("Bob"); mS.push("Sally"); mS.push("Lucy"); The Stack Should now look like this: Lucy Sally Bob Joe Billy 20 String o = mS.pop( ); String s = mS.pop( ); String y = mS.peek( ); boolean ee = mS.empty(); The Stack Should now look like this: Bob Joe Billy The String y contains “Bob” The Boolean empty is False 21 Errors: The pop and peek methods can throw an Unchecked Exception IndexOutOfBOundsException or NoSuchElementException in cases where the stack is empty 22 If you use the ArrayList or the LinkedList Java class to implement your Stack, then these errors are handled , for you, from within these classes 23 Queues: Its lunch time and you leave class early to get into the food line “SaLee” dashes as fast as he can and is first to grab a tray and get into line After SaLee, “AJ” trips over a floor tile and skins his knee 24 As a result, “Eli” stops to help wipe away AJ’s tears and to give him a Scooby Doo bandaid So, Eli winds up behind SalLee and AJ follows Since the line is implemented as a Queue, SalLee gets the best lunch choices and AJ gets the crumbs 25 TO implement a Queue ADT, you must provide a way to store (add) and remove (remove) elements from a Queue Elements on the Queue should be of the same type (or in the same class hierarchy) A Queue has no limits as to its size 26 TO add an element on to the Queue you “add” that item and it goes to the end of the Queue TO remove an element from the Queue, you can only “remove” off the element currently at the top of the Queue 27 ADD --- adds elements to the end of the Queue REMOVE --- removes the element from the top of the Queue These operations should be in Constant time O(1) 28 Other behaviors of the Queue should return the top element of the Queue without removing it (peek) and to see if the Queue has any elements left in it (isEmpty) For our purposes, we will use the Java standard Queue Interface: 29 public interface Queue { // postcondition: returns true if queue is empty, false otherwise boolean isEmpty(); // precondition: queue is [e1, e2, ..., en] with n >= 0 // postcondition: queue is [e1, e2, ..., en, x] void enqueue(Object x); // precondition: queue is [e1, e2, ..., en] with n >= 1 // postcondition: queue is [e2, ..., en]; returns e1 // throws an unchecked exception if the queue is empty Object dequeue(); // precondition: queue is [e1, e2, ..., en] with n >= 1 // postcondition: returns e1 // throws an unchecked exception if the queue is empty Object peekFront(); } 30 As we can see, the QUEUE is merely an Interface in Java and can be Implemented using specific data structures. The LinkedList class supports the rules of the Queue ADT and therefore is the preferred implementation of a Queue. 31 The College Board uses this implementation to execute a Queue, therefore you must understand the LinkedList methods that will PERFORM the list as a QUEUE. boolean add(E x) E remove() E peek() boolean isEmpty() 32 Therefore, the QUEUE interface method OFFER is implemented in the LinkedList class as add We will examine the following code that utilizes a LinkedList AS A QUEUE, however, you will implement your own QUEUE. 33 As far as the AP requirements, understanding the rules of the QUEUE ADT as well as the BIG-O and the LinkedList implementation will suffice, however, you will be held responsible, for our tests, for everything we cover in class and accomplish in our labs. 34 Here is a Queue example: LinkedList<Integer> r = new LinkedList<Integer>(); r.add(32); r.add(64); r.add(128); for(Integer x:r) { System.out.println(x.toString()); } r.remove(); System.out.println( r.isEmpty()); System.out.println( r.peek()); 35 Ring Buffer An array used in a circular manner. Adjust the pointer that defines the “logical” first array element. The state of the queue is maintained with the help of 2 indices, FRONT and REAR. 36 Front points to the first element in the queue (returned by the next call to the remove) Rear points to the empty slot following the last stored element. Add method stores the next element in the slot pointed to by the rear and increments the rear index. 37 PC’s have a keyboard queue implemented as a ring buffer. When a key is pressed its code does not go directly to the active program but is placed in the keyboard buffer until the program requests it. 38 Queues are best when simulating bank lines, or any other system where there is a “First Come First Served” basis 39 BIG-O Operation Insert/Add Stack push O(1) Queue add O(1) Remove pop O(1) remove O(1) Peek peek O(1) peek O(1) 40 TPS: Implement a Queue by Writing your own Class Implement the Possible Unchecked Exceptions 41 AP AB Subset Requirements: stacks, queues and priority queues always refer to the conceptual data structure e.g. don’t add to the middle of a queue 42 AP AB Subset Requirements: students who carry out operations in a free-response question that are incompatible with the conceptual nature of a data structure may not receive full credit 43 AP AB Subset Requirements: Students are also responsible for understanding that these ADT’s can be implemented as an array or a linked list, although you will NOT be tested on any SPECIFIC implementation 44 AP AB Subset Requirements: You will see Multiple Choice questions regarding analysis of Stack and Queue implementations and processes Multiple Choice questions may focus on your ability to evaluate the effectiveness of and to determine the best use of Stacks and Queues 45 Projects: Barrons M/C Questions Chapter 9 p.310 Do ALL Questions Except the following: # 14, 15 Decimal to Binary Expression McDonalds Palendrome 46 TEST FOLLOWS COMPLETION OF PROJECTS !!! 47