/** * Remove and return the element at the back of the linked list. * * @return the element that was at the back of the linked list * @throws NoSuchElementException if attempting to remove from an empty list */ public T removeFromBack() { if (isEmpty()) { throw new NoSuchElementException(); } DLNode<T> oldTail = getTail(); if (getTail().getPrevious() != null) { // fix next for new tail and set new tail getTail().getPrevious().setNext(null); setTail(getTail().getPrevious()); } else { // removed last node setTail(null); setHead(null); } return oldTail.getElement(); }
/** * Remove and return the element at the front of the linked list. * * @return the element that was at the front of the linked list * @throws NoSuchElementException if attempting to remove from an empty list */ public T removeFromFront() { if (isEmpty()) { throw new NoSuchElementException(); } DLNode<T> oldHead = getHead(); if (getHead().getNext() != null) { // fix previous for new head and set new head getHead().getNext().setPrevious(null); setHead(getHead().getNext()); } else { // removed last node setHead(null); setTail(null); } return oldHead.getElement(); }
/** * Returns a string representation of the contents of the linked list, from the front to the back. * * @return a string representation of the linked list, from front to back */ public String toString() { if (isEmpty()) { return ""; } else if (getHead() == getTail()) { // one element return getHead().getElement().toString(); } else { StringBuilder newString = new StringBuilder(); DLNode<T> placeHolder = getHead(); // loop through and build string node by node while (placeHolder.getNext() != null) { newString.append(placeHolder.getElement().toString()); placeHolder = placeHolder.getNext(); } newString.append(placeHolder.getElement().toString()); return newString.toString(); } }
/** * {@inheritDoc} * * @return returns next element from list */ public DLNode<T> next() { if (iterNode == null) { // end of list so no more elements throw new NoSuchElementException(); } else { // increment iterNode and return previous value DLNode<T> temp = iterNode; iterNode = iterNode.getNext(); return temp; } }