//a simpler linked list implementation without parametric polymorphism and Iterator //Author: Konstantin Voevodski //Date: 6/4/07 public class mySimpleLinkedList { private static class Node { public int data; public Node prev; public Node next; public Node(int d, Node p, Node n) { data = d; prev = p; next = n; } } private int size; private int modCount = 0; private Node beginMarker; private Node endMarker; public mySimpleLinkedList() { clear(); } public void clear() { beginMarker = new Node(-1,null,null); endMarker = new Node(-1,beginMarker,null); //it is irrelevant what is stored in the data field of beginMarker and endMarker beginMarker.next = endMarker; size = 0; modCount++; } public int size() { return size; } public boolean isEmpty() { return(size == 0); } private void addBefore(Node p, int 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++; modCount++; } private int remove(Node p) //remove node p, conceptually modifying two links { p.next.prev = p.prev; p.prev.next = p.next; size--; modCount++; 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(int x) { add(size(),x); return true; } public void add(int index, int x) { addBefore(getNode(index),x); } public int get(int index) { return (getNode(index).data); } public int set(int index, int newVal) { Node p = getNode(index); int oldVal = p.data; p.data = newVal; return oldVal; } public int remove(int index) { return(remove(getNode(index))); } }