package solution; public class SimpleLinkedList extends AbstractSimpleList { Node firstNode; int size; public SimpleLinkedList() { firstNode = null; size = 0; } @Override public int size() { return size; } @Override public boolean add(E e) { if (e == null) { return false; } else if (firstNode == null) { firstNode = new Node(e); } else { Node currentNode = firstNode; while (currentNode != null) { if (currentNode.getSuccessor() == null) { break; } currentNode = currentNode.getSuccessor(); } Node newNode = new Node(e); currentNode.setSuccessor(newNode); newNode.setPredecessor(currentNode); } size++; return true; } @Override public boolean remove(Object o) { if (o == null) { return false; } Node currentNode = firstNode; while (currentNode != null) { if (o.equals(currentNode.getPayload())) { currentNode.setPayload(null); size--; return true; } if (currentNode.getSuccessor() == null) { break; } currentNode = currentNode.getSuccessor(); } return false; } @Override public boolean contains(Object o) { if (o == null) { return false; } Node currentNode = firstNode; while (currentNode != null) { if (o.equals(currentNode.getPayload())) { return true; } currentNode = currentNode.getSuccessor(); } return false; } @Override public void forAll(ICommand command) { if (command != null) { Node currentNode = firstNode; while (currentNode != null) { command.execute(currentNode.getPayload()); currentNode = currentNode.getSuccessor(); } } } private Node getIndex(int i) { if (i < 0 || size <= i) { return null; } Node currentNode = firstNode; int currentIndex = 0; while (currentNode != null) { if (currentIndex >= i) { if (currentNode.getPayload() != null) { return currentNode; } } currentNode = currentNode.getSuccessor(); currentIndex++; } return null; } public E get(int i) throws IndexOutOfBoundsException { return getIndex(i).getPayload(); } public void set(int i, E e) throws IndexOutOfBoundsException { getIndex(i).setPayload(e); } public boolean remove(int i) throws IndexOutOfBoundsException { if (getIndex(i) != null) { getIndex(i).setPayload(null); size--; return true; } return false; } public void add(int i, E e) throws IndexOutOfBoundsException { if (size == 0) { if (i != 0) { throw new IndexOutOfBoundsException("Index " + i + " is out of bounds!"); } set(0, e); } else if (i == size) { add(e); } else if (size > 0 && i < size) { Node newNode = new Node<>(e);// node3 Node tempNode = getIndex(i); // node2 Node preTempNode = getIndex(i).getPredecessor(); // node1 preTempNode.setSuccessor(newNode); newNode.setPredecessor(preTempNode); newNode.setSuccessor(tempNode); tempNode.setPredecessor(newNode); } } }