//a generic linked list implementation //Author: Konstantin Voevodski import java.util.*; public class myLinkedList { private static class Node { public AnyType data; public Node prev; public Node next; public Node(AnyType d, Node p, Node n) { data = d; prev = p; next = n; } } private int size; private Node beginMarker; private Node endMarker; public myLinkedList() { clear(); } public void clear() { beginMarker = new Node(null,null,null); endMarker = new Node(null,beginMarker,null); beginMarker.next = endMarker; size = 0; } public int size() { return size; } public boolean isEmpty() { return(size == 0); } private void addBefore(Node p, AnyType x) //add new node before p, conceptually modifying four links { Node newNode = new Node(x,p.prev,p); newNode.prev.next = newNode; p.prev = newNode; size++; } private AnyType remove(Node p) //remove node p, conceptually modifying two links { p.next.prev = p.prev; p.prev.next = p.next; size--; return p.data; } private Node getNode(int idx) //return a Node at the given index { if(idx < 0 || idx > size()) { throw new IndexOutOfBoundsException(); } Node p; if(idx < size()/2) //traverse list from the front { p = beginMarker.next; for(int i = 0; i < idx; i++) { p = p.next; } } else //traverse list from the back { p = endMarker; for(int i = size(); i > idx; i--) { p = p.prev; } } return p; } public boolean add(AnyType x) { add(size(),x); return true; } public void add(int index, AnyType x) { addBefore(getNode(index),x); } public AnyType get(int index) { return (getNode(index).data); } public AnyType set(int index, AnyType newVal) { Node p = getNode(index); AnyType oldVal = p.data; p.data = newVal; return oldVal; } public AnyType remove(int index) { return(remove(getNode(index))); } }