/* DequeViaLink2.java ** An instance of this class represents a deque ("Double Ended QUEue") ** which combines the capabilities of a stack and a queue. That is, in ** a deque, elements can be inserted at both the front and the rear, and ** likewise removed from both the front and the rear. Only the elements ** at the front and at the rear can be observed. ** ** Authors: R. McCloskey and < STUDENTS' NAMES > ** Known Defects: ... ** Date: October 2022 */ public class DequeViaLink2 implements Deque { // instance variables // ------------------ private Link2 front; // reference/pointer to front node private Link2 rear; // reference/pointer to rear node private int numItems; // how many items occupy this deque // constructor // ----------- /* Initializes this deque to be empty. */ public DequeViaLink2() { front = null; rear = null; numItems = 0; } // observers // --------- /* Reports whether or not this deque is empty (i.e. has no elements in it). */ public boolean isEmpty() { return sizeOf() == 0; } /* Reports whether or not this deque is full, meaning that an attempt ** to insert an item may fail. */ public boolean isFull() { return false; } /* Reports how many items occupy this deque. */ public int sizeOf() { return numItems; } /* Returns (a reference to) the item at the front of this deque. ** pre: !isEmpty() */ public T frontOf() { return front.item; } /* Returns (a reference to) the item at the rear of this deque. ** pre: !isEmpty() */ public T rearOf() { return null; // STUB! (See frontOf()) } /* Returns a list of the (images of the) items in the deque, ** going from front to rear, enclosed in square brackets. */ public String toString() { StringBuilder result = new StringBuilder("[ "); Link2 pntr = front; while (pntr != null) { result.append(pntr.item + " "); pntr = pntr.next; } result.append(']'); return result.toString(); } // mutators // -------- /* Removes the item at the front of this deque. ** pre: !isEmpty() */ public void removeFront() { if (front == rear) { front = null; rear = null; } else { //STUB! // < MISSING CODE > (See removeRear()) } numItems--; } /* Removes the item at the rear of this deque. ** pre: !isEmpty() */ public void removeRear() { if (front == rear) { //STUB! // < MISSING CODE > (See removeFront()) } else { rear = rear.prev; rear.next = null; } numItems--; } /* Inserts the specified item at the front of this deque. */ public void insertAtFront(T elem) { // STUB (See insertAtRear()) } /* Inserts the specified item at the rear of this deque. */ public void insertAtRear(T elem) { Link2 newRear = new Link2(elem); newRear.prev = rear; if (rear == null) { front = newRear; } else { rear.next = newRear; } rear = newRear; numItems++; } }