Queue ADT. B/W Confirming Pages

Size: px
Start display at page:

Download "Queue ADT. B/W Confirming Pages"

Transcription

1 wu23399_ch20.qxd 1/2/07 20:56 Page Queue ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the Queue ADT. Implement the Queue ADT by using an array. the Queue ADT by using a Implement linked list. the key differences between the array Explain and linked implementations of the Queue ADT. a special type of queue called a Implement priority queue. 1069

2 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT I n t r o d u c t i o n Our study of the fundamental ADTs concludes with the Queue ADT in this chapter. Just as the Stack ADT is natural and intuitive because stacks are ubiquitous in our everyday, physical world, so is the Queue ADT. The Queue ADT is almost identical to the Stack ADT except for the one key difference, and often it is treated as an inseparable sibling of the Stack ADT. The Queue ADT models a line of objects, such as people or vehicles, waiting to be serviced. Students waiting in line to pay for food at the cashier in the student union cafeteria, moviegoers waiting in line to enter the 16-screen cineplex, and vehicles waiting in line at the signal-controlled freeway on-ramp are all examples of queues. The defining feature of a queue is that the object at the front of the queue is the next to be serviced (imagine the ensuing chaos and havoc at Disney s Space Mountain if you randomly picked people in line for the next ride) and a new object is added to the end, or tail, of the queue. As in the previous chapters, we begin with the definition of the Queue ADT and then provide two different implementations based on the array and the linked list. We will conclude the chapter with a special variation of a queue called a priority queue. queue tail front add 20.1 The Queue ADT A queue is a linearly ordered collection of elements in which elements, or items, are added to a list at one end, called the tail, and removed from the other end, called the front. This restriction will ensure that the first element added to a list is the first to be removed next. For this reason, a queue is characterized as a first-in, first-out (FIFO) list. Figure 20.1 shows a sample generic queue named samplequeue with five elements and another queue named myqueue with five three-letter animal names. The operations we support in the Queue ADT are almost identical to those in the Stack ADT. The clear, isempty, peek, and size operations behave the same as those of the Stack ADT. The clear operation empties a queue. The isempty operation returns true if the queue contains no items. The peek operation returns the front item, without actually removing it. The size operation rereturns the number of items in the queue. The update operations for the queue are called add and remove. They are also called enqueue and dequeue, respectively. The add operation adds an item to the tail of a queue, and the remove operation removes the item at the front of a queue. We will describe these operations in greater detail. The add operation will add the designated element to the tail of the queue. The queue does not have any size restriction, so it will grow without bound, just as the stack does. There is no restriction on the elements, so you can add duplicates. Figure 20.2 illustrates the add operation.

3 wu23399_ch20.qxd 1/2/07 20:56 Page The Queue ADT 1071 samplequeue front tail E 0 E 1 E 2 E 3 E 4 myqueue front tail "ape" "dog" "bee" "dog" "eel" Figure 20.1 A generic stack samplequeue with five elements and a stack myqueue with three-letter animal names. myqueue Before "cat" "ape" "dog" myqueue add("bat") After "cat" "ape" "dog" "bat" Figure 20.2 A sample add operation on the myqueue queue. remove peek clear The remove operation removes the front element from the queue if there is any. If the queue is empty, then the operation will throw an exception. Figure 20.3 illustrates the remove operation on nonempty and empty stacks. The peek operation is just like the remove operation except that the front element is not removed from the queue. If the queue is empty, then the operation will throw an exception. The clear operation removes all elements in the queue. It causes no problem to call the clear operation on an empty queue. This operation is useful when you want to reuse a queue. Before you reuse the queue for another purpose, you need to flush out any remaining items in the queue, and you can do it by calling the clear

4 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT myqueue Before "cat" "ape" "dog" "bat" myqueue remove( ) returns "cat" After "ape" "dog" "bat" myqueue Before remove( ) throws <exception> After myqueue Figure 20.3 Sample remove operations on the myqueue queue. size isempty operation, instead of removing items individually by calling the remove method repeatedly. The size operation returns the number of elements in the queue. The isempty operation tests whether the queue is empty. If it is, then true is returned. Otherwise, false is returned. 1. Draw the queue after executing the following operations, starting with an empty queue called myqueue. String bee = new String("bee"); String cat = new String("cat");

5 wu23399_ch20.qxd 1/2/07 20:56 Page The Queue Interface 1073 myqueue.clear( ); myqueue.add(bee); myqueue.add(cat); myqueue.remove( ); 2. Repeat Question 1 with the following statements: String bee = new String("bee"); String cat = new String("cat"); String dog = new String("dog"); myqueue.add(bee); myqueue.add(cat); myqueue.add(dog); myqueue.peek( ); myqueue.remove( ); myqueue.remove( ); myqueue.add(dog); 20.2 The Queue Interface As we did for the List and Stack ADTs, we will use a Java interface to define the Queue ADT. We will continue to prefix our interfaces and classes with NPS. Here s the NSPQueue interface: NPSQueue package edu.nps.util; public interface NPSSQueue<E> { public void add(e element); public void clear( ); public boolean isempty( ); public E peek( ) throws NPSQueueEmptyException; public E remove( ) throws NPSQueueEmptyException; public int size( );

6 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT Table 20.1 The NPSQueue interface Table Interface: NPSStack void add( E element ) Adds an element to the queue. The element is added to the tail of the queue. void clear( ) Removes all elements from the queue. boolean isempty( ) Determines whether the queue is empty. Returns true if it is empty;false otherwise. E peek( ) throws NPSQueueEmptyException Returns the front element without removing it from the queue. Throws an exception when the queue is empty. E remove( ) throws NPSQueueEmptyException Removes the front element and returns it. Throws an exception when the queue is empty. int size( ) Returns the number of elements in the queue. Table 20.1 summarizes the methods of the NPSQueue interface. Analogous to the implementation of the Stack ADT, the peek and remove methods are defined to throw an NPSQueueEmptyException. It is based on our design philosophy to use an exception that identifies the error condition as precisely as possible, instead of using a generic exception. Here s the definition: NPSQueueEmptyException package edu.nps.util; public class NPSQueueEmptyException extends RuntimeException { public NPSQueueEmptyException( ) { this("queue is empty"); public NPSQueueEmptyException(String message) { super(message);

7 wu23399_ch20.qxd 1/2/07 20:56 Page The Array Implementation The Array Implementation In this section, we will implement the NPSQueue interface by using an array to store the queue elements. Figure 20.4 illustrates the array implementation of the Queue ADT. The NPSArrayQueue Definition The NPSArrayQueue class implements the NPSStack interface, and its class declaration is as follows: package edu.nps.util; public class NPSArrayQueue<E> implements NPSQueue<E> { //class body comes here We use an array element to store the queue elements and an int variable count to keep track of the number of elements currently in the queue. In addition, we use two int variables front and tail to keep track of the index positions of the element array to remove an item from and add an item to the queue. These data members are declared as private static final int DEFAULT_SIZE = 25; private E[ ] element; ADT Queue myqueue "cat" "ape" "dog" "bat" myqueue Array Implementation :NPSArrayQueue element n 1 count 4 front 0 :String :String :String :String tail 4 "cat" "ape" "dog" "bat" Figure 20.4 An array implementation of the Queue ADT.

8 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT private int count; //number of items in the queue private int front; //position of the item to remove private int tail; //position to add the next item We will define two constructors: one takes no argument and another takes one argument that specifies the initial size of the array. They are defined as follows: public NPSArrayQueue( ) { this(default_size); public NPSArrayQueue(int size) { if (size <= 0) { throw new IllegalArgumentException( "Initial capacity must be positive"); element = (E[]) new Object[size]; clear( ); add We create an array of Object and typecast it to an array of E, the type parameter, because it is not allowed to create an array of generic type in Java. We maintain the data member tail to keep track of the index position of the element array to add an item. So we might think that the code element[tail] = item; tail++; would suffice (provided, of course, that the overflow condition is handled by creating a new, larger array, as we did with the expand method in the NPSArrayList and NPSArrayStack classes). But this clean and straightforward solution would not work for the queue. Why? The code does not work because we cannot increment the value of tail beyond element.length-1. Doing so would result in an IndexOutOfBoundsException. Easy, just create a new, larger array when the current value of tail becomes equal to element.length? It is not appropriate to do so because the condition does not indicate the array is full. Consider the following scenario. Suppose the size of the element array is N and you execute N adds followed by N removes. Since every time we remove the front item we need to increment front so it points to the new front item, the values of front and tail would be N 1 and N, respectively. Do you want to create a new, larger array at this point? No, the queue is actually empty. Creating a larger array when the queue is empty is grossly inefficient. What shall we do? We should create a larger array only when the array is full, and we detect this condition when the variable count is equal to element.length. The trick here to avoid the value of counters becoming larger than element.length-1 is to view the

9 wu23399_ch20.qxd 1/2/07 20:56 Page The Array Implementation 1077 tail Increment operations: tail = (tail + 1) % N; 4 front = (front + 1) % N; 3 2 front 1 0 N 1 N 2 N 3 - Occupied cell Figure 20.5 This illustrates viewing an array as if it were circular. The index counters move in a clockwise fashion. By using modulo arithmetic, the value of the index counters never gets beyond N 1. After N 1, the counters are reset to 0. element array as a circular array. Figure 20.5 illustrates a circular array with four items. We treat an array as if it is circular by using the modulo arithmetic when incrementing the index counters tail = (tail + 1) % N; front = (front + 1) % N; where N is the size (length) of the array. For example, when tail is equal to N 1, incrementing it will result in tail having the value 0. By using this modulo arithmetic, the counters move round and round in clockwise fashion. The add method is defined as follows: public void add(e item) { //check if full if (count == element.length) { expand( ); element[tail] = item; tail = (tail + 1) % element.length; count++; The expand method for the NPSArrayQueue class is a lot more complex than the corresponding method in the NPSArrayList and the NPSArrayStack classes because the array is circular in NPSArrayQueue. It is no longer a simple matter of copying elements at index position I in one array to the same index position I of

10 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT Before 1 2 d a c b 0 3 tail front front 1 2 a 0 After 3 b c d 5 4 tail original_array[2] original_array[3] original_array[0] original_array[1] Copy new_larger_array[2] new_larger_array[3] new_larger_array[4] new_larger_array[5] Figure 20.6 This illustrates how the expand method works for the circular array.the length of the original array is 4, and the front of the queue is stored at index position 2. Notice how the items are copied to the expanded array. The value of front remains the same, but the value of tail needs to be adjusted as shown. the expanded array. Consider the example shown in Figure The length of the original array is 4. The front item of the queue is stored at index position 2. When the overflow occurs, the condition front == tail is true. We create a new array that is 1.5 times larger than the original array, so the length of the new array is 6. Then we start copying the elements from the original array to the new larger array, starting from the front item. Because both arrays are circular, we cannot simply write something like for (int i = front; i < tail; i++) { new_larger_array[i] = original_array[i]; INVALID Although conceptually this is what we want to do, the actual indices we need here must be incremented cyclically. Here s the correct procedure to copy items from a circular array element to a new and larger circular array temp: int e_idx = front; int t_idx = front; for (int i = 0; i < count; i++) { //count - # of items // in queue temp[t_idx] = element[e_idx]; t_idx = (t_idx + 1) % temp.length; e_idx = (e_idx + 1) % element.length; tail = t_idx;

11 wu23399_ch20.qxd 1/2/07 20:56 Page The Array Implementation 1079 remove This operation removes the front element from the queue. If the queue is not empty, we adjust the count data member and remove the topmost element by setting the value of the corresponding index position to null. Here s the method: public E remove() throws NPSQueueEmptyException { E item; if (isempty( )) { throw new NPSQueueEmptyException( ); else { item = element[front]; element[front] = null; front = (front + 1) % element.length; count--; return item; clear We set element[i] to null, where i =0,..., count-1, so the objects referenced by element[i] will be garbage-collected. We then reset the three variables to 0 to reflect the empty state. public void clear( ) { for (int i = 0; i < count; i++) { element[i] = null; front = tail = count = 0; isempty This operation is straightforward. If the value of count is 0, then the stack is empty. Otherwise, the stack is not empty. public boolean isempty( ) { return (count == 0); peek We throw an NPSQueueEmptyException when the queue is empty. Otherwise, we return the front item. public E peek() throws NPSQueueEmptyException { if (isempty( )) { throw new NPSQueueEmptyException( ); else {

12 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT return element[front]; size The last method is straightforward. We simply return the value of the count data member. public int size ( ) { return count; Here s the complete source code (for brevity, javadoc and most other comments in the actual source file are removed here): NPSArrayQueue package edu.nps.util; public class NPSArrayQueue<E> implements NPSQueue<E> { private static final int DEFAULT_SIZE = 25; private E[ ] element; private int count; private int front; private int tail; public NPSArrayQueue( ) { Constructor this(default_size); public NPSArrayQueue(int size) { if (size <= 0) { throw new IllegalArgumentException( "Initial capacity must be positive"); element = (E[]) new Object[size]; count = 0; public void add(e item) { add if (count == element.length) { expand( );

13 wu23399_ch20.qxd 1/2/07 20:56 Page The Array Implementation 1081 tail = (tail + 1) % element.length; count++; public void clear() { clear for (int i = 0; i < count; i++) { element[i] = null; front = tail = count = 0; public boolean isempty() { isempty return count == 0; public E peek( ) throws NPSQueueEmptyException { peek if (isempty( )) { throw new NPSQueueEmptyException( ); else { return element[front]; public E remove() throws NPSQueueEmptyException { remove E item; if (isempty( )) { throw new NPSQueueEmptyException( ); else { item = element[front]; element[front] = null; front = (front + 1) % element.length; count--; return item; public int size( ) { size return count;

14 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT private void expand( ) { expand E[] temp = (E[]) new Object[(int)(1.5 * element.length)]; int e_idx = front; int t_idx = front; for (int i = 0; i < count; i++) { temp[t_idx] = element[e_idx]; t_idx = (t_idx + 1) % temp.length; e_idx = (e_idx + 1) % element.length; tail = t_idx; element = temp; 1. Draw the array queue (like the diagram in Figure 20.4) after executing the following operations, starting with an empty queue called myqueue. String bee = new String("bee"); String cat = new String("cat"); myqueue.clear(); myqueue.add(cat); myqueue.add(bee); 2. Can we use the test front == tail to detect the empty queue? 20.4 The Linked-List Implementation Compared to the array implementation of the List and Stack ADTs, the array implementation of the Queue ADT has an increased complexity of dealing with the circular array. Fortunately, the linked-list implementation of the Queue ADT does not incur any additional complexity. Its implementation is rather straightfoward. Figure 20.7 illustrates the linked-list implementation of the Queue ADT. The QueueNode Class The linked node structure for the queue is exactly the same as the one for the list and the stack. The QueueNode class is defined as the inner class of the NPSLinkedQueue

15 wu23399_ch20.qxd 1/2/07 20:56 Page The Linked-List Implementation 1083 myqueue ADT Queue "cat" "ape" "dog" "bat" myqueue Linked-List Implementation :NPSArrayQueue tail front count 4 :String :String :String :String "cat" "ape" "dog" "bat" Figure 20.7 A linked-list implementation of the stack myqueue. class. It s class definition is as follows: class QueueNode { private E item; private QueueNode next; public QueueNode(E item) { this.item = item; this.next = null; The NPSLinkedQueue Class We keep three data members in the class. As always, we have one data member to keep track of the number of items currently in the queue. The other two data members front and tail are reference variables that point to the front and tail elements. Their declarations are private QueueNode front; private QueueNode tail; private int count;

16 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT We define only a single constructor that takes no arguments and sets the stack to its initial state, which is an empty queue. The constructor is defined as follows: public NPSLinkedQueue( ) { clear( ); add There are two cases to consider when adding a new item. In the first case, the queue is empty. In this case, we set both front and tail to the new item. In the second case, the queue is not empty. In this case, we append the new item as the last node in the linked list and need to adjust the tail pointer only. In both cases, we increment the counter variable count by 1. Here s the method: public void add(e item) { QueueNode newnode = new QueueNode(item); if (isempty()) { front = tail = newnode; else { tail.next = newnode; tail = newnode; count++; clear We reset the two pointers front and tail to null and the counter count to 0. By setting front and tail to null, all nodes in the linked list will get garbage-collected eventually. Here s the clear method: public void clear( ) { front = tail = null; count = 0; isempty We detect the queue is empty when the value of count is 0: public boolean isempty( ) { return count == 0; peek If the queue is empty, we throw an NPSQueueEmptyException. Otherwise, we return the front item (without actually removing it). Here s the method: public E peek( ) throws NPSQueueEmptyException { if (isempty( )) {

17 wu23399_ch20.qxd 1/2/07 20:56 Page The Linked-List Implementation 1085 throw new NPSQueueEmptyException( ); else { return front.item; remove If the queue is empty, we throw an NPSQueueEmptyException. Otherwise, we set a temp pointer to the topmost item, update the topofstack pointer, and return the topmost item. Here s the method: public E remove( ) throws NPSQueueEmptyException { E item; if (isempty( )) { throw new NPSQueueEmptyException( ); else { item = front.item; front = front.next; count--; return item; size The size method simply returns the value of the data member count: public int size( ) { return count; Here s the complete source code listing of the NPSLinkedQueue class (as usual, javadoc comments are omitted for brevity): NPSLinkedQueue package edu.nps.util; public class NPSLinkedQueue<E> implements NPSQueue<E> { private QueueNode front; private QueueNode tail; private int count;

18 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT public NPSLinkedQueue( ) { clear( ); public void add(e item) { Constructor add QueueNode newnode = new QueueNode(item); if (isempty()) { front = tail = newnode; else { tail.next = newnode; tail = newnode; count++; public void clear( ) { clear front = tail = null; count = 0; public boolean isempty( ) { isempty return (count == 0); public E peek( ) throws NPSQueueEmptyException { peek if (isempty( )) { throw new NPSQueueEmptyException( ); else { return front.item; public E remove( ) throws NPSQueueEmptyException { remove E item; if (isempty( )) { throw new NPSQueueEmptyException( );

19 wu23399_ch20.qxd 1/2/07 20:56 Page The Linked-List Implementation 1087 else { item = front.item; front = front.next; count--; return item; public int size( ) { size return count; class QueueNode { QueueNode private E item; private Queue next; public QueueNode(E item) { this.item = item; this.next = null; 1. Draw the linked stack (like the right-hand side diagram in Figure 20.7) after executing the following operations, starting with an empty stack called myqueue. String bee = new String("bee"); String cat = new String("cat"); myqueue.clear(); myqueue.push(cat); myqueue.push(bee); 2. Instead of using count == 0 to check for an empty stack, can we use front == null or tail == null?

20 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT 20.5 Implementation Using NPSList Analogous to the NPSListStack class, we can define a class that implements the NPSQueue interface easily by using an NPSList. Here s the NPSListQueue class: NPSListQueue package edu.nps.util; public class NPSListQueue<E> implements NPSQueue<E> { private static final int FRONT = 0; private NPSList<E> list; public NPSListQueue( ) { list = new NPSLinkedList<E>(); public void add(e element) { list.add(list.size(), element); public void clear( ) { list.clear(); public boolean isempty( ) { return list.isempty(); public E peek( ) throws NPSQueueEmptyException { Constructor add clear isempty peek if (isempty( )) { throw new NPSQueueEmptyException( ); else { return list.get(front); public E remove( ) throws NPSQueueEmptyException { remove if (isempty( )) { throw new NPSQueueEmptyException( ); else { return list.remove(front);

21 wu23399_ch20.qxd 1/2/07 20:56 Page Priority Queue 1089 public int size( ) { return list.size(); size The class is implemented cleanly and elegantly by using a list. Since a queue is a FIFO list, we add a new item at the end of the list and remove only the first (front) item of the list. priority queue 20.6 Priority Queue With a queue, items are treated fairly and equally. An item that arrives first in line is the first to be served next. In real life, queues do not always follow this egalitarian rule. Travelers are routinely moved up to the front of the security line at the airport when their flights are departing soon. Partygoers who know the right people never wait in line to get into the hottest nightclub in town. In many situations, we have legitimate reasons to prioritize items in the queue so the highest-priority item is served next. See Exercise 9 for a computer-related example. A priority queue is a queue in which items are prioritized so that the item with the highest priority is placed at the front of the queue. Every time a new item is added, the queue is rearranged so the highest-priority item will always be at the front. In this section, we describe how such a priority queue can be implemented very effectively by using the heap structure we introduced in Chapter 11. We will call the class NPSPriorityQueue that realizes the priority queue. It is a queue so we set the class to implement the NPSQueue interface: public class NPSPriorityQueue<E extends Comparable> implements NPSQueue<E> We will use the heap structure to maintain the priority queue (see Section 11.3). When we add an item, we place it as the last node of the heap and go through the construction process so the highest-priority item will move to the root of the heap. Remember that the construction process includes approximately N 2 rebuilding processes (see Figure 11.14). The remove method will remove the root of the heap. After the removal, we need to rebuild the heap with one fewer item. We do this by moving (temporarily) the last node of the heap to the root position and going through the rebuilding process once (see Figure 11.11). To be able to move around items in the heap, we need to decide how to compare the priorities of items. First, we dictate that the type parameter E implement the Comparable interface; that is, E must include the method compareto. Second, the compareto method must defined in the following manner: e1.compareto(e2) < 0 e1 has higher priority than e2 e1.compareto(e2) == 0 e1 and e2 has the same priority e1.compareto(e2) > 0 e1 has lower priority than e2

22 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT Remember that we used an array to implement the heap structure in Chapter 11. We will use the same technique here to implement the heap structure we need for the NPSPriorityQueue class. Implementation of the NPSPriorityQueue class is basically a combination of the code that appeared in the NPSArrayQueue class and the Heap class (from Chapter 11) with some necessary modifications. As such, we will just go ahead and list the complete class now, skipping the explanation of the methods that are essentially identical to those we ve seen already. NPSPriorityQueue package edu.nps.util; public class NPSPriorityQueue<E> implements NPSQueue<E> { private static final int DEFAULT_SIZE = 25; private static final int ROOT = 0; private E[] heap; private int count; public NPSPriorityQueue( ) { Constructors this(default_size); public NPSPriorityQueue(int size) { if (size <= 0) { throw new IllegalArgumentException( "Initial capacity must be positive"); heap = (E[])new Object[size]; clear(); public void add(e item) { add if (count == heap.length) { expand( ); heap[count] = item; construct(); count++;

23 wu23399_ch20.qxd 1/2/07 20:56 Page Priority Queue 1091 public void clear() { for (int i = 0; i < count; i++) { heap[i] = null; clear count = 0; public boolean isempty( ) { return count == 0; public E peek() throws NPSQueueEmptyException { isempty peek if (isempty()) { throw new NPSQueueEmptyException( ); else { return (E) heap[root]; public E remove() throws NPSQueueEmptyException { remove E item; if (isempty()) { throw new NPSQueueEmptyException( ); else { item = heap[root]; heap[root] = heap[count-1]; count--; rebuild(root); return item; public int size( ) { size return count; private void construct( ) { construct for (int i = (count-2) / 2; i >= 0; i--) {

24 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT rebuild(i); private void expand( ) { expand E[] temp = (E[])new Object[(int) (heap.length * 1.5)]; for (int i = 0; i < heap.length; i++) { temp[i] = heap[i]; heap = temp; private int higherprioritychild(int location, int end) { int result, leftchildindex, rightchildindex; higherprioritychild rightchildindex = 2*location + 2; leftchildindex = 2*location + 1; if ( rightchildindex <= end && ((Comparable<E>)heap[leftChildIndex]). compareto(heap[rightchildindex]) < 0) { result = leftchildindex; else { result = rightchildindex; return result; private void rebuild(int root) { rebuild int current = root; boolean done = false; while (!done) { if (2*current+1 > count-1) { //current node has no children, so stop done = true; else { //current node has at least one child, //get the index of higher-priority child int hichildindex = higherprioritychild(current, count-1);

25 wu23399_ch20.qxd 1/2/07 20:56 Page Priority Queue 1093 if ((Comparable<E>)heap[hiChildIndex]). compareto(heap[current]) < 0) { swap(current, hichildindex); current = hichildindex; else { //value relationship constraint //is satisfied, so stop done = true; private void swap(int loc1, int loc2) { swap E temp; temp = heap[loc1]; heap[loc1] = heap[loc2]; heap[loc2] = temp; Here s a short sample code that illustrates the use of NPSPriorityQueue. The program adds 100 random integers (ranges from 0 to 999, inclusive) and removes them one by one from the priority. The output list will display integers in ascending order. import java.util.*; import edu.nps.util.*; class TestPriorityQueue { public static void main(string[] args) { NPSQueue<Integer> pq = new NPSPriorityQueue<Integer>(); Random random = new Random(); for (int i = 0; i < 100; i++) { pq.add(random.nextint(1000)); for (int j = 0; j < 100; j++) { System.out.println(pq.remove());

26 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT S u m m a r y Aqueue is a linearly ordered first-in, first-out (FIFO) collection of elements. An item can be added to only the end of a queue, and only the first item of a queue can be removed. The last item is called the tail of a queue, and the first item is called the front. An array and a linked list are two possible implementations of the Queue ADT. The Queue ADT can be implemented easily by using a list (an instance of a class that implements the List ADT). Base implementation of the Queue ADT does not support any traversal operation. Apriority queue is a special type of queue that moves the highest-priority item to the front of the queue. K e y C o n c e p t s queue ADT array implementation of Queue ADT linked-list implementation of Queue ADT priority queue E x e r c i s e s 1. Draw a state-of-memory diagram that shows the result of executing each of the following sets of code. Do not forget to show the values of front and tail. a. b. NPSQueue queue = new NPSArrayQueue(5); queue.add("one"); queue.add("two"); queue.add("three"); queue.add("four"); queue.remove( ); queue.remove( ); NPSQueue queue = new NPSLinkedQueue( ); queue.add("one"); queue.add("two"); queue.add("three"); queue.add("four"); queue.remove( ); queue.remove( );

27 wu23399_ch20.qxd 1/2/07 20:56 Page 1095 Exercises Add a new method toarray to the NPSQueue interface and implement the method in both NPSArrayQueue and NPSLinkedQueue. The toarray method will return an array with the front element at position 0, the element after the front at position 1, and so forth. 3. Add a new method iterator to the NPSQueue interface that returns an iterator. Implement the iterator method in the NPSArrayQueue and NPSLinkedQueue classes. 4. Although the use of the count data member makes the implementation of the NPSArrayQueue class cleaner and slightly easier, its use is not a strict requirement. You can implement the class without it. Rewrite the NPSArrayQueue class with the count data member removed. You have to find out the number of items in the queue from the values of front and tail data members. Because the array is circular, you cannot simply use the expression tail - front to determine the number of items in the queue. Also, you have to be very careful in detecting the array is full. Hint: If the length of an array is N, occupy at most N 1 positions. Treat the array is full when N 1 positions are filled. 5. Redo Exercise 4 with the NPSLinkedQueue class. Without the count data member, you must traverse the linked list to find out how many items are in the queue. 6. Write a program that sorts input strings in lexicographic order by using the NPSPriorityQueue class. Continually prompt for the next input word until the end marker 1 is entered. Terminate the program after printing out the input words in lexicographic order, one word per line. Notice that the String class already implements the Comparable interface so no additional effort is necessary for you to add String objects to an NPSPriorityQueue. The priority queue treats a string that comes earlier in lexicographic order as having a higher priority. For example, the word cat has a higher priority than dog. 7. Repeat Exercise 6, but this time output the words in reverse lexicographic order. You are not allowed to change the implementation of the NPSPriorityQueue class. Although the source code of NPSPriorityQueue is available to you, treat it as if it is a part of some standard API. 8. Write a bank ATM simulation program. The purpose of this simulation is to find out the average waiting time for customers using the ATMs. There are three inputs to the program: M is the number of minutes to simulate, P is the probability of a customer arriving at each minute, and N is the number of ATMs. For example, if the input values for M, P, and N are 60, 0.5, and 4, respectively, then we are simulating 4 ATMs during a 60-minute period with 50 percent chance that a customer arrives at each minute. When a customer arrives, randomly assign a number between 1 minute and 5 minutes, inclusive, as this customer s transaction time, the time it takes for this

28 wu23399_ch20.qxd 1/2/07 20:56 Page Chapter 20 Queue ADT customer to finish using the ATM. Each ATM has its own queue, and an arriving customer will move to the shortest queue. An ATM is either available (open) or not available (currently used by another customer). When a customer completes his or her transaction, an ATM becomes available immediately. And if there s a customer waiting in the queue, the ATM will service this customer immediately (and becomes unavailable). Each minute is treated as a discrete event, so the top-level simulation control can be expressed as a for loop: for (int min = 0; min < M; min++) { //process incoming customer if (a new customer arrives) { assign him/her to the shortest queue //process ATMs for (int i = 0; i < N; i++) { if (ATM[i] is in use) { decrement the transaction time of its customer by 1; if (the remaining time of the customer == 0) { //this customer is done set the status of ATM[i] to available if (ATM[i] is available) { //pick the next customer from //the queue if there's one if (ATM[i] has customer in its queue) { remove the customer form the queue, set his/her waiting time, and assign him/her to ATM[i] At the end of simulation, output the average waiting time along with the input values. Run the program multiple times. Experiment with different values for P and N to see the effect. For instance, you should expect to see an increase in average waiting times if you keep the values for M and P the same, but decrease the value for N, say, from 4 to 1. Notice that when the outer for loop [for (int min = 0; min < M; min++)] exits, it is possible that the queues may still contain customers. There are two possible ways to handle the situation. The first way is to assume that all

29 wu23399_ch20.qxd 1/2/07 20:56 Page 1097 Exercises 1097 those waiting customers will be served immediately (you can say that the bank will open up as many ATMs as necessary to serve immediately). The second way is to continue the simulation loop until all queues are empty. For this exercise, you may choose either solution. 9. Write a job scheduling simulation program. In good old days, well before the PC revolution, computer science students wrote programs by using keypunch machines and ran them on the mainframe computers. A program is recorded on a stack of punch cards, one statement per punch card. To run their programs, students must submit the program (the stack of cards) to the computer operator. A submitted program is called a job. Students taking a computer course are assigned a certain number of units (kind of a virtual money) and charged N units to run a program. The actual amount charged is determined by the priority the students assign to their programs. For this exercise, assume that the priorities range from 1 to 5, with 1 being the highest. Write a program that simulates the job scheduling. Inputs to the program are M, which is the number of minutes to simulate, and N, which is the number of jobs that the computer can run concurrently. Treat each minute as a discrete event. Assume that a single job arrives at each minute. When a job arrives, randomly assign its priority and the number of minutes it needs to be executed. Choose any integer between 1 minute and 10 minutes, inclusive, for the execution time. An arriving job is placed in a priority queue. At every discrete event, if the number of jobs assigned to the computer is below the maximum number of jobs the computer can handle, remove jobs from the priority queue and assign them to the computer. At the end of the simulation, output the average waiting time and the maximum waiting time for each priority level. See Exercise 8 on how to handle the situation in which the queue is not empty at the end of simulated minutes.

30 wu23399_ch20.qxd 1/2/07 20:56 Page 1098

List ADT. B/W Confirming Pages

List ADT. B/W Confirming Pages wu3399_ch8.qxd //7 :37 Page 98 8 List ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the List ADT. the List ADT using an array

More information

Stack ADT. B/W Confirming Pages

Stack ADT. B/W Confirming Pages wu23399_ch19.qxd 1/2/07 20:46 Page 1035 19 Stack ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the Stack ADT. Develop applications

More information

CSE 2123: Collections: Priority Queues. Jeremy Morris

CSE 2123: Collections: Priority Queues. Jeremy Morris CSE 2123: Collections: Priority Queues Jeremy Morris 1 Collections Priority Queue Recall: A queue is a specific type of collection Keeps elements in a particular order We ve seen two examples FIFO queues

More information

Programming and Data Structures Prof. N.S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Programming and Data Structures Prof. N.S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras Programming and Data Structures Prof. N.S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 13 Merging using Queue ADT and Queue types In the

More information

Linked List. ape hen dog cat fox. tail. head. count 5

Linked List. ape hen dog cat fox. tail. head. count 5 Linked Lists Linked List L tail head count 5 ape hen dog cat fox Collection of nodes with a linear ordering Has pointers to the beginning and end nodes Each node points to the next node Final node points

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof. Priority Queues 1 Introduction Many applications require a special type of queuing in which items are pushed onto the queue by order of arrival, but removed from the queue based on some other priority

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

More information

Queues. October 20, 2017 Hassan Khosravi / Geoffrey Tien 1

Queues. October 20, 2017 Hassan Khosravi / Geoffrey Tien 1 Queues October 20, 2017 Hassan Khosravi / Geoffrey Tien 1 Queue ADT Queue ADT should support at least the first two operations: enqueue insert an item to the back of the queue dequeue remove an item from

More information

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 3, January 21) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Abstraction In Homework 1, you were asked to build a class called Bag. Let

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 11 Introduction to Computing II Wayne Snyder Department Boston University Today Object-Oriented Programming Concluded Stacks, Queues, and Priority Queues as Abstract Data Types Reference types: Basic

More information

Queues. CITS2200 Data Structures and Algorithms. Topic 5

Queues. CITS2200 Data Structures and Algorithms. Topic 5 CITS2200 Data Structures and Algorithms Topic 5 Queues Implementations of the Queue ADT Queue specification Queue interface Block (array) representations of queues Recursive (linked) representations of

More information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

DEEPIKA KAMBOJ UNIT 2. What is Stack? What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE TED (10)-3071 Reg. No.. (REVISION-2010) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours (Maximum marks: 100)

More information

CSE 214 Computer Science II Heaps and Priority Queues

CSE 214 Computer Science II Heaps and Priority Queues CSE 214 Computer Science II Heaps and Priority Queues Spring 2018 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Introduction

More information

CSCI 200 Lab 11 A Heap-Based Priority Queue

CSCI 200 Lab 11 A Heap-Based Priority Queue CSCI 200 Lab 11 A Heap-Based Priority Queue Preliminaries Part of today s lab will focus on implementing a heap-based priority queue using an ArrayListlike class called ZHExtensibleArrayStructure. Recall

More information

1. Introduction. Lecture Content

1. Introduction. Lecture Content Lecture 6 Queues 1 Lecture Content 1. Introduction 2. Queue Implementation Using Array 3. Queue Implementation Using Singly Linked List 4. Priority Queue 5. Applications of Queue 2 1. Introduction A queue

More information

Queues. ADT description Implementations. October 03, 2017 Cinda Heeren / Geoffrey Tien 1

Queues. ADT description Implementations. October 03, 2017 Cinda Heeren / Geoffrey Tien 1 Queues ADT description Implementations Cinda Heeren / Geoffrey Tien 1 Queues Assume that we want to store data for a print queue for a student printer Student ID Time File name The printer is to be assigned

More information

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice Name Section Number CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice All Sections Bob Wilson OPEN BOOK / OPEN NOTES: You will have all 90 minutes until the start of the next class period.

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 10: Search and Heaps MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Search and Heaps 2 Linear Search Binary Search Introduction to trees Priority Queues Heaps Linear Search

More information

1 P age DS & OOPS / UNIT II

1 P age DS & OOPS / UNIT II UNIT II Stacks: Definition operations - applications of stack. Queues: Definition - operations Priority queues - De que Applications of queue. Linked List: Singly Linked List, Doubly Linked List, Circular

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Queues ArrayQueue Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 10, 2014 Abstract These lecture notes are meant to be looked

More information

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S Stacks Stacks & Queues A linear sequence, or list, is an ordered collection of elements: S = (s 1, s 2,..., s n ) Stacks and queues are finite linear sequences. A Stack is a LIFO (Last In First Out) list.

More information

Advanced Java Concepts Unit 3: Stacks and Queues

Advanced Java Concepts Unit 3: Stacks and Queues Advanced Java Concepts Unit 3: Stacks and Queues Stacks are linear collections in which access is completely restricted to just one end, called the top. Stacks adhere to a last-in, first-out protocol (LIFO).

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

Midterm Exam (REGULAR SECTION)

Midterm Exam (REGULAR SECTION) Data Structures (CS 102), Professor Yap Fall 2014 Midterm Exam (REGULAR SECTION) October 28, 2014 Midterm Exam Instructions MY NAME:... MY NYU ID:... MY EMAIL:... Please read carefully: 0. Do all questions.

More information

STUDENT LESSON AB30 Binary Search Trees

STUDENT LESSON AB30 Binary Search Trees STUDENT LESSON AB30 Binary Search Trees Java Curriculum for AP Computer Science, Student Lesson AB30 1 STUDENT LESSON AB30 Binary Search Trees INTRODUCTION: A binary tree is a different kind of data structure

More information

CS 61B Midterm 2 Guerrilla Section Spring 2018 March 17, 2018

CS 61B Midterm 2 Guerrilla Section Spring 2018 March 17, 2018 CS 61B Midterm 2 Guerrilla Section Spring 2018 March 17, 2018 Instructions Form a small group. Start on the first problem. Check off with a helper or discuss your solution process with another group once

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues INFO1x05 Tutorial 6 Heaps and Priority Queues Exercise 1: 1. How long would it take to remove the log n smallest elements from a heap that contains n entries, using the operation? 2. Suppose you label

More information

4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING

4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING 4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING 4.1.2 ALGORITHMS ALGORITHM An Algorithm is a procedure or formula for solving a problem. It is a step-by-step set of operations to be performed. It is almost

More information

Introduction to Computing II (ITI 1121) Final Examination

Introduction to Computing II (ITI 1121) Final Examination Université d Ottawa Faculté de génie École de science informatique et de génie électrique University of Ottawa Faculty of Engineering School of Electrical Engineering and Computer Science Introduction

More information

COMP 250 Midterm #2 March 11 th 2013

COMP 250 Midterm #2 March 11 th 2013 NAME: STUDENT ID: COMP 250 Midterm #2 March 11 th 2013 - This exam has 6 pages - This is an open book and open notes exam. No electronic equipment is allowed. 1) Questions with short answers (28 points;

More information

CSCE 2014 Final Exam Spring Version A

CSCE 2014 Final Exam Spring Version A CSCE 2014 Final Exam Spring 2017 Version A Student Name: Student UAID: Instructions: This is a two-hour exam. Students are allowed one 8.5 by 11 page of study notes. Calculators, cell phones and computers

More information

Postfix (and prefix) notation

Postfix (and prefix) notation Postfix (and prefix) notation Also called reverse Polish reversed form of notation devised by mathematician named Jan Łukasiewicz (so really lü-kä-sha-vech notation) Infix notation is: operand operator

More information

12 Abstract Data Types

12 Abstract Data Types 12 Abstract Data Types 12.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT). Define

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more

More information

Collections and Iterators. Collections

Collections and Iterators. Collections Collections and Iterators Based on the notes from David Fernandez-Baca and Steve Kautz Based on The Java Tutorial (http://docs.oracle.com/javase/tutorial/java/) Bryn Mawr College CS206 Intro to Data Structures

More information

Section 05: Solutions

Section 05: Solutions Section 05: Solutions 1. Memory and B-Tree (a) Based on your understanding of how computers access and store memory, why might it be faster to access all the elements of an array-based queue than to access

More information

CE204 Data Structures and Algorithms Part 2

CE204 Data Structures and Algorithms Part 2 CE204 Data Structures and Algorithms Part 2 14/01/2018 CE204 Part 2 1 Abstract Data Types 1 An abstract data type is a type that may be specified completely without the use of any programming language.

More information

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES CH4.2-4.3. ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER

More information

Heaps. Heaps. A heap is a complete binary tree.

Heaps. Heaps. A heap is a complete binary tree. A heap is a complete binary tree. 1 A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. A min-heap is defined

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Readings List Implementations Chapter 20.2 Objectives Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Additional references:

More information

CSE 373 Data Structures and Algorithms. Lecture 2: Queues

CSE 373 Data Structures and Algorithms. Lecture 2: Queues CSE 373 Data Structures and Algorithms Lecture 2: Queues Queue ADT queue: A list with the restriction that insertions are done at one end and deletions are done at the other First-In, First-Out ("FIFO

More information

CSCI 200 Lab 3 Using and implementing sets

CSCI 200 Lab 3 Using and implementing sets CSCI 200 Lab 3 Using and implementing sets In this lab, you will write a program that manages a set of workers, using the Worker hierarchy you developed in Lab 2. You will also implement your own version

More information

Queues. Queue ADT Queue Implementation Priority Queues

Queues. Queue ADT Queue Implementation Priority Queues Queues Queue ADT Queue Implementation Priority Queues Queue A restricted access container that stores a linear collection. Very common for solving problems in computer science that require data to be processed

More information

CS 3114 Data Structures and Algorithms READ THIS NOW!

CS 3114 Data Structures and Algorithms READ THIS NOW! READ THIS NOW! Print your name in the space provided below. There are 7 short-answer questions, priced as marked. The maximum score is 100. This examination is closed book and closed notes, aside from

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked lists, allow insertion and deletion of elements

More information

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10 Keeping Order:! Stacks, Queues, & Deques 1 Stacks 2 Stacks A stack is a last in, first out (LIFO) data structure Primary Operations: push() add item to top pop() return the top item and remove it peek()

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3 UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between

More information

Data Abstraction and Specification of ADTs

Data Abstraction and Specification of ADTs CITS2200 Data Structures and Algorithms Topic 4 Data Abstraction and Specification of ADTs Example The Reversal Problem and a non-adt solution Data abstraction Specifying ADTs Interfaces javadoc documentation

More information

Queue rear tail front head FIFO

Queue rear tail front head FIFO The Queue ADT Objectives Examine queue processing Define a queue abstract data type Demonstrate how a queue can be used to solve problems Examine various queue implementations Compare queue implementations

More information

csci 210: Data Structures Stacks and Queues

csci 210: Data Structures Stacks and Queues csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks

More information

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm Part 1 (50 pts) due: October 13, 2013 11:59pm Part 2 (150 pts) due: October 20, 2013 11:59pm Important Notes This assignment is to be done on your own. If you need help, see the instructor or TA. Please

More information

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM

More information

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Queues CSE 2011 Fall 2009 9/28/2009 7:56 AM 1 Queues: FIFO Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Applications,

More information

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures Final Examination (17 pages) Instructor: Douglas Harder April 14, 2004 9:00-12:00 Name (last,

More information

CSCI Lab 9 Implementing and Using a Binary Search Tree (BST)

CSCI Lab 9 Implementing and Using a Binary Search Tree (BST) CSCI Lab 9 Implementing and Using a Binary Search Tree (BST) Preliminaries In this lab you will implement a binary search tree and use it in the WorkerManager program from Lab 3. Start by copying this

More information

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures 1.00 Lecture 26 Data Structures: Introduction Stacks Reading for next time: Big Java: 19.1-19.3 Data Structures Set of primitives used in algorithms, simulations, operating systems, applications to: Store

More information

Introduction to Linked Data Structures

Introduction to Linked Data Structures Introduction to Linked Data Structures A linked data structure consists of capsules of data known as nodes that are connected via links Links can be viewed as arrows and thought of as one way passages

More information

Data Structures and Algorithms. Chapter 5. Dynamic Data Structures and Abstract Data Types

Data Structures and Algorithms. Chapter 5. Dynamic Data Structures and Abstract Data Types 1 Data Structures and Algorithms Chapter 5 and Abstract Data Types Werner Nutt 2 Acknowledgments The course follows the book Introduction to Algorithms, by Cormen, Leiserson, Rivest and Stein, MIT Press

More information

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Linda Shapiro Spring 2016

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Linda Shapiro Spring 2016 CSE373: Data Structures & Algorithms Lecture : Priority Queues and Binary Heaps Linda Shapiro Spring 2016 A new ADT: Priority Queue A priority queue holds compare-able data Like dictionaries, we need to

More information

Stacks, Queues (cont d)

Stacks, Queues (cont d) Stacks, Queues (cont d) CSE 2011 Winter 2007 February 1, 2007 1 The Adapter Pattern Using methods of one class to implement methods of another class Example: using List to implement Stack and Queue 2 1

More information

[2:3] Linked Lists, Stacks, Queues

[2:3] Linked Lists, Stacks, Queues [2:3] Linked Lists, Stacks, Queues Helpful Knowledge CS308 Abstract data structures vs concrete data types CS250 Memory management (stack) Pointers CS230 Modular Arithmetic !!!!! There s a lot of slides,

More information

LIFO : Last In First Out

LIFO : Last In First Out Introduction Stack is an ordered list in which all insertions and deletions are made at one end, called the top. Stack is a data structure that is particularly useful in applications involving reversing.

More information

Before class. BSTs, Heaps, and PQs 2/26/13 1. Open TreeNodeExample.java Change main to:

Before class. BSTs, Heaps, and PQs 2/26/13 1. Open TreeNodeExample.java Change main to: Before class Open TreeNodeExample.java Change main to: 1 public static void main(string[] args) { 2 for(int j = 4; j < 1; j++){ 3 TreeNodeExample tree = new TreeNodeExample(); 4 double start = System.currentTimeMillis();

More information

A Linked Structure. Chapter 17

A Linked Structure. Chapter 17 Chapter 17 A Linked Structure This chapter demonstrates the OurList interface implemented with a class that uses a linked structure rather than the array implementation of the previous chapter. The linked

More information

CS165 Practice Midterm Problems Fall 2018

CS165 Practice Midterm Problems Fall 2018 CS165 Practice Midterm Problems Fall 2018 The following is a collection of practice problems for the CS165: Data Structures and Applications second midterm. The questions are similar to what they would

More information

Where does the insert method place the new entry in the array? Assume array indexing starts from 0(zero).

Where does the insert method place the new entry in the array? Assume array indexing starts from 0(zero). Suppose we have a circular array implementation of the queue,with ten items in the queue stored at data[2] through data[11]. The current capacity of an array is 12. Where does the insert method place the

More information

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES Midterm Examination Douglas Wilhelm Harder 1.5 hrs, 2005/02/17 11 pages Name (last, first):

More information

Cosc 241 Programming and Problem Solving Lecture 21 (15/5/2017) Heaps

Cosc 241 Programming and Problem Solving Lecture 21 (15/5/2017) Heaps 1 Cosc 241 Programming and Problem Solving Lecture 21 (15/5/2017) Heaps Michael Albert michael.albert@cs.otago.ac.nz Keywords: heap 2 Heaps A binary tree is complete if it is full and balanced and all

More information

Problem 1: Building and testing your own linked indexed list

Problem 1: Building and testing your own linked indexed list CSCI 200 Lab 8 Implementing a Linked Indexed List In this lab, you will be constructing a linked indexed list. You ll then use your list to build and test a new linked queue implementation. Objectives:

More information

You must include this cover sheet. Either type up the assignment using theory5.tex, or print out this PDF.

You must include this cover sheet. Either type up the assignment using theory5.tex, or print out this PDF. 15-122 Assignment 5 Page 1 of 11 15-122 : Principles of Imperative Computation Fall 2012 Assignment 5 (Theory Part) Due: Tuesday, October 30, 2012 at the beginning of lecture Name: Andrew ID: Recitation:

More information

DNHI Homework 3 Solutions List, Stacs and Queues

DNHI Homework 3 Solutions List, Stacs and Queues Solutions List, Stacs and Queues Problem 1 Given the IntegerQueue ADT below state the return value and show the content of the, initially empty, queue of Integer objects after each of the following operations.

More information

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

ext Total Score /20 /20 /15 /20 /25 /5 Grader

ext Total Score /20 /20 /15 /20 /25 /5 Grader NAME: NETID: CS2110 Fall 2013 Prelim 2 November 21, 2013 Write your name and Cornell netid. There are 5 questions plus one extra-credit question on 10 numbered pages. Check now that you have all the pages.

More information

CE 221 Data Structures and Algorithms

CE 221 Data Structures and Algorithms CE 2 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, 6.1 6.3 Izmir University of Economics 1 A kind of queue Priority Queue (Heap) Dequeue gets element with the

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today Introduction to Linked Lists Stacks and Queues using Linked Lists Next Time Iterative Algorithms on Linked Lists Reading:

More information

Queues Fall 2018 Margaret Reid-Miller

Queues Fall 2018 Margaret Reid-Miller Queues 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Writing methods various classes that implement Lists. Methods using Lists and Big-O w/ ArrayList or LinkedLists Prove

More information

PRIORITY QUEUES AND HEAPS

PRIORITY QUEUES AND HEAPS 10//1 Readings and Homework Read Chapter A Heap Implementation to learn about heaps PRIORITY QUEUES AND HEAPS Lecture 17 CS10 Fall 01 Exercise: Salespeople often make matrices that show all the great features

More information

COMP 250 Fall priority queues, heaps 1 Nov. 9, 2018

COMP 250 Fall priority queues, heaps 1 Nov. 9, 2018 COMP 250 Fall 2018 26 - priority queues, heaps 1 Nov. 9, 2018 Priority Queue Recall the definition of a queue. It is a collection where we remove the element that has been in the collection for the longest

More information

Lecture Data Structure Stack

Lecture Data Structure Stack Lecture Data Structure Stack 1.A stack :-is an abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards

More information

Lecture 13: AVL Trees and Binary Heaps

Lecture 13: AVL Trees and Binary Heaps Data Structures Brett Bernstein Lecture 13: AVL Trees and Binary Heaps Review Exercises 1. ( ) Interview question: Given an array show how to shue it randomly so that any possible reordering is equally

More information

Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems. COMP Week 8 & 9 1

Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems. COMP Week 8 & 9 1 Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems COMP 202 - Week 8 & 9 1 A recursive definition is one which uses the word or concept being

More information

Stacks and Queues III

Stacks and Queues III EE Data Structures and lgorithms http://www.ecs.umass.edu/~polizzi/teaching/ee/ Stacks and Queues III Lecture 8 Prof. Eric Polizzi Queues overview First In First Out (FIFO) Input D Output Queues allow

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

Arrays. Chapter Arrays What is an Array?

Arrays. Chapter Arrays What is an Array? Chapter 8 Arrays 81 Arrays 811 What is an Array? To motivate why we might be interested in using arrays, let us implement an app that creates a collection of doubles We will keep track of the number of

More information

Arrays and Linked Lists

Arrays and Linked Lists Arrays and Linked Lists Abstract Data Types Stacks Queues Priority Queues and Deques John Edgar 2 And Stacks Reverse Polish Notation (RPN) Also known as postfix notation A mathematical notation Where every

More information

Queues. Data Structures and Design with Java and JUnit Rick Mercer 18-1

Queues. Data Structures and Design with Java and JUnit Rick Mercer 18-1 Queues Data Structures and Design with Java and JUnit Rick Mercer 18-1 A Queue ADT First in first out access A Queue is another name for waiting line Example: Submit jobs to a network printer What gets

More information

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue Priority Queues (0F) Lecture: Heaps Bohyung Han CSE, POSTECH bhhan@postech.ac.kr Queues Stores items (keys) in a linear list or array FIFO (First In First Out) Stored items do not have priorities. Priority

More information

Stacks and Queues. Chapter Stacks

Stacks and Queues. Chapter Stacks Chapter 18 Stacks and Queues 18.1 Stacks The stack abstract data type allows access to only one element the one most recently added. This location is referred to as the top of the stack. Consider how a

More information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

CS/CE 2336 Computer Science II

CS/CE 2336 Computer Science II CS/CE 2336 Computer Science II UT D Session 11 OO Data Structures Lists, Stacks, Queues Adapted from D. Liang s Introduction to Java Programming, 8 th Ed. 2 What is a Data Structure? A collection of data

More information

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination University of Illinois at Urbana-Champaign Department of Computer Science Second Examination CS 225 Data Structures and Software Principles Spring 2014 7-10p, Tuesday, April 8 Name: NetID: Lab Section

More information

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer) COSC 2007 Data Structures II Final Exam Thursday, April 13 th, 2006 This is a closed book and closed notes exam. There are total 3 parts. Please answer the questions in the provided space and use back

More information

Section 01: Solutions

Section 01: Solutions Section 01: Solutions 1. CSE 143 review 1.1. Reference semantics Quick Check 2 [0, 1] 1 [0, 1] 1 [1, 2] 0 [1, 2] 0 [0, 0] 0 [1, 2] (a) What is the output of this program? public class Mystery2 { public

More information