package chimomo.learning.ds; /** * @author Chimomo * @param <T> */ public interface List<T> { public int size(); public boolean isEmpty(); public void insert(int index, T obj) throws Exception; public void delete(int index) throws Exception; public T get(int index) throws Exception; }
package chimomo.learning.ds; /** * @author Chimomo * @param <T> */ public class LinkList<T> implements List<T> { Node<T> head; Node<T> current; int size; // Construct an empty linklist public LinkList() { head = current = new Node<T>(null); this.size = 0; } // Position before the node which to be operated public void position(int index) throws Exception { if (index < -1 || index > size - 1) { throw new Exception("Wrong index!"); } if (index == -1) { return; } current = head.next; int j = 0; while (current != null && j < index) { current = current.next; j++; } } @Override public int size() { return this.size; } @Override public boolean isEmpty() { return this.size == 0; } @Override public void insert(int index, T obj) throws Exception { if (index < 0 || index > size) { throw new Exception("Wrong index!"); } position(index - 1); current.setNext(new Node<T>(obj, current.next)); size++; } @Override public void delete(int index) throws Exception { if (isEmpty()) { throw new Exception("Link list is empty, cannot delete!"); } if (index < 0 || index > size) { throw new Exception("Wrong index!"); } position(index - 1); current.setNext(current.next.next); size--; } @Override public T get(int index) throws Exception { if (index < -1 || index > size - 1) { throw new Exception("Wrong index!"); } position(index); return current.getElement(); } class Node<T> { T element; Node<T> next; // Constructor for head node public Node(Node<T> nextNode) { this.next = nextNode; } // Constructor for non-head node public Node(T obj, Node<T> nextNode) { this.element = obj; this.next = nextNode; } public T getElement() { return this.element; } public Node<T> getNext() { return this.next; } public void setElement(T obj) { this.element = obj; } public void setNext(Node<T> nextNode) { this.next = nextNode; } @Override public String toString() { return this.element.toString(); } } }
package chimomo.learning.ds; /** * @author Chimomo */ public class LinkListTest { public static void main(String[] args) throws Exception { LinkList<Integer> intList = new LinkList<Integer>(); for (int i = 0; i < 10; i++) { int t = ((int) (Math.random() * 100)) % 100; intList.insert(i, t); System.out.print(t + " "); } System.out.println(); System.out.println("List size: " + intList.size()); System.out.println("List is empty? " + intList.isEmpty()); intList.insert(5, 6); for (int i = 0; i < intList.size(); i++) { System.out.print(intList.get(i) + " "); } System.out.println(); intList.delete(4); for (int i = 0; i < intList.size(); i++) { System.out.print(intList.get(i) + " "); } System.out.println(); System.out.println("Get element at 6: " + intList.get(5)); } }