/** An instance of this class represents a queue capable of holding items ** of the specified type T (the generic type parameter). ** The underlying implementation makes use of a linked structure of ** objects arising from the Link1 class. ** ** Author: R. McCloskey ** Date: January 2020 */ public class QueueViaLink1 implements Queue { // instance variables // ------------------ protected Link1 front; // reference to object holding front item on queue protected Link1 rear; // reference to object holding rear item on queue private int numItems; // # of items on the queue // constructors // ------------ /* Establishes this queue as being empty. */ public QueueViaLink1() { clear(); } // observers // --------- public int sizeOf() { return numItems; } public boolean isEmpty() { return sizeOf() == 0; } public boolean isFull() { return false; } public T frontOf() { return front.item; } @Override public String toString() { Link1 pntr = front; StringBuilder result = new StringBuilder("[ "); for (int i=0; i != numItems; i++) { result.append(pntr.item + " "); pntr = pntr.next; } return result.append(']').toString(); } // mutators // -------- public void clear() { front = null; rear = null; numItems = 0; } public void enqueue( T item ) { Link1 newRear = new Link1(item, null); if (isEmpty()) { front = newRear; } else { rear.next = newRear; } rear = newRear; numItems = numItems + 1; } public T dequeue() { T result = front.item; front = front.next; numItems = numItems - 1; return result; } }