/** * Returns the data stored at the specified index. * * @param index The index determines the node whose data is returned. * @return Returns the data of the node at the index. */ public E get(int index) { // returns the data stored at the specified index int currIndex = 0; DoubleLinkedNode<E> currNode = this.head; E temp = null; if (index == 0) { // zero case temp = currNode.getData(); } else if (index > 0) { // positive while (currIndex != size) { if (currIndex != index % size) { currIndex++; currNode = currNode.getNext(); } else { temp = currNode.getData(); break; } } } else if (index < 0) { // negative while (currIndex != -size) { if (currIndex != index % size) { currIndex--; currNode = currNode.getPrev(); } else { temp = currNode.getData(); break; } } } return temp; }
/** * Which removes and returns an item from the list. * * @param index Removes the node at the current index. * @return Returns the data of the removed node. */ public E remove(int index) { // which removes and returns an item from the list int currIndex = 0; DoubleLinkedNode<E> currNode = this.head; DoubleLinkedNode<E> nextNode = this.head.getNext(); DoubleLinkedNode<E> prevNode = this.head.getPrev(); E temp = null; if (index == 0) { temp = currNode.getData(); prevNode.setNext(currNode.getNext()); nextNode.setPrev(currNode.getPrev()); this.head = nextNode; size--; } else if (index > 0) { // positive while (currIndex != size) { if (currIndex != index % size) { currIndex++; currNode = currNode.getNext(); nextNode = nextNode.getNext(); prevNode = prevNode.getNext(); } else { temp = currNode.getData(); prevNode.setNext(currNode.getNext()); nextNode.setPrev(currNode.getPrev()); currNode = nextNode; size--; break; } } } else if (index < 0) { // negative while (currIndex != -size) { if (currIndex != index % size) { currIndex--; currNode = currNode.getPrev(); prevNode = prevNode.getPrev(); nextNode = nextNode.getPrev(); } else { temp = currNode.getData(); prevNode.setNext(currNode.getNext()); nextNode.setPrev(currNode.getPrev()); currNode = prevNode; size--; break; } } } return temp; }
@Override public E previous() { if (!hasPrevious()) { throw new NoSuchElementException("No such element."); } else { prevItem = head; lastReturned = prevItem.getPrev(); prevItem = prevItem.getPrev(); head = prevItem; index--; return lastReturned.getData(); } }
@Override public E next() { if (!hasNext()) { throw new NoSuchElementException("No such element."); } else { nextItem = head; lastReturned = nextItem; nextItem = nextItem.getNext(); head = nextItem; index++; return lastReturned.getData(); } }
@Override public String toString() { String str = "["; int index = 0; DoubleLinkedNode<E> curr = head; if (size == 0) { return "There is no one here to kill."; } else { while (index < size) { str += curr.getData(); curr = curr.getNext(); index++; if (index < size) { str += ", "; } } str += "]"; } return str; }