/** An instance of this class represents a queue capable of holding items of ** type T (the generic type parameter). ** The implementation is based on storing the queue items in a linked ** structure of objects arising from the Link1 class. ** ** Author: R. McCloskey ** Date: March 2012 */ public class QueueViaLink1 implements Queue { /* i n s t a n c e v a r i a b l e s */ private Link1 front; // reference to Link1 object holding front item private Link1 rear; // reference to Link1 object holding rear item private int numItems; // # of items on the queue /* c o n s t r u c t o r s */ public QueueViaLink1() { front = null; rear = null; numItems = 0; } /* o b s e r v e r s */ public int sizeOf() { return numItems; } public boolean isEmpty() { return sizeOf() == 0; } public T frontOf() { return front.item; // alternative: return front.getItem(); // alternative: return item(0) } public T item(int k) { Link1 p = front; // have p begin at the front for (int i=0; i!=k; i++) { // follow next references k times p = p.next; // alternative: p = p.getNext(); } // return the item in the node to which p points return p.item; // alternative: return p.getItem(); } public String toString() { StringBuilder s = new StringBuilder(); Link1 p = front; while (p != null) { s.append(p.item.toString() + ","); p = p.next; } return s.substring(0,Math.max(0, s.length()-1)); } // Alternative O(N^2)-time loop for above method // final int N = sizeOf(); // for (int i=0; i != N; i++) { // s.append(item(i).toString() + ","); // } /* m u t a t o r s */ public void enqueue(T elem) { Link1 newRear = new Link1(elem, null); if (isEmpty()) { front = newRear; } else { rear.next = newRear; // alternative: rear.setNext(newRear); } rear = newRear; numItems = numItems + 1; } public void dequeue() { front = front.next; // or front = front.getNext(); numItems = numItems - 1; if (front == null) { rear = null; } // not necessary } }