import java.util.*; /** * A ListNode object is a singly-linked list node, which stores a value and a link to the next node. */ class ListNode { public ListNode(E data, ListNode next){ this.data = data; this.next = next; } public E data; public ListNode next; } /** * A MyList object is a singly-linked list. This class implements the List interface. * This implementation is still under construction. */ class MyList implements List { public MyList(){} public MyList(E[] a){ for (E e: a){ add(e); } }; public boolean add(E e){ if (tail == null){ head = tail = new ListNode(e, null); } else { ListNode p = new ListNode(e, null); tail.next = p; tail = p; } return true; } public void add(int index, E element){ if (index < 0) throw new IndexOutOfBoundsException("add"); if (index == 0 && head == null) add(element); ListNode cur, pre; cur = head; pre = null; while (cur != null && index > 0){ pre = cur ; cur = cur.next; index--; } if (index > 0) throw new IndexOutOfBoundsException("add"); ListNode p = new ListNode(element,cur); if (pre == null){ head = p; } else { pre.next = p; } }; public boolean addAll(Collection c){return true;}; public boolean addAll(int index, Collection c){return true;}; public void clear(){}; public boolean contains(Object o){return true;}; public boolean containsAll(Collection c){return true;}; public boolean equals(Object o){return true;}; public E get(int index){return null;}; public int hashCode(){return 0;}; public int indexOf(Object o){return 0;}; public boolean isEmpty(){ return head == null; }; public Iterator iterator(){return null;}; public int lastIndexOf(Object o){return 0;}; public ListIterator listIterator(){return null;}; public ListIterator listIterator(int index){return null;}; public E remove(int index){return null;}; public boolean remove(Object o){return true;}; public boolean removeAll(Collection c){return true;}; public boolean retainAll(Collection c){return true;}; public E set(int index, E element){ if (index < 0) throw new IndexOutOfBoundsException("add"); ListNode cur = head; while (cur != null && index > 0){ cur = cur.next; index--; } if (index > 0 || cur == null) throw new IndexOutOfBoundsException("add"); E oldVal = cur.data; cur.data = element; return oldVal; } public int size(){ int count = 0; ListNode cur = head; while (cur != null){ count++; cur = cur.next; } return count; }; public List subList(int fromIndex, int toIndex){return null;} public Object[] toArray(){return new Object[0];}; public E[] toArray(E[] a){return a;}; public String toString(){ StringBuffer sb = new StringBuffer(); ListNode cur = head; sb.append('['); while (cur != null){ sb.append(cur.data.toString()); if (cur != tail) sb.append(','); cur = cur.next; } sb.append(']'); return sb.toString(); } private ListNode head, tail; public static void main(String[] args){ Integer[] a = {1,2,3,4,5}; MyList lst = new MyList(a); System.out.println(lst); lst.add(0,0); System.out.println(lst); } }