import java.util.Iterator; class MyLinkedList { Node head; public void addFirst(E x){ head = new Node(x,head); } public void add(E x){ if (head == null){ head = new Node(x); } else { Node pre,curr; pre = curr = head; while (curr != null){ pre = curr; curr = curr.getNext(); } pre.setNext(new Node(x)); } } class MyLinkedListIterator implements Iterator { Node curNode; public MyLinkedListIterator(MyLinkedList l){ curNode = l.head; } public E next(){ E val; if (curNode!=null){ val = curNode.getVal(); curNode = curNode.getNext(); return val; } return null; } public boolean hasNext(){ return curNode!=null; } public void remove(){} } public Iterator iterator(){ return new MyLinkedListIterator(this); } public void print(){ Iterator it = iterator(); while (it.hasNext()){ E e = it.next(); System.out.print(e+" "); } System.out.println(); } public static void main(String[] args){ MyLinkedList lst = new MyLinkedList(); lst.add(2); lst.add(3); lst.addFirst(1); lst.print(); } } class Node { E val; Node next; public Node(E x, Node next){ val = x; this.next = next; } public Node(E x){ this(x,null); } public void setNext(Node next){ this.next = next; } public Node getNext(){ return this.next; } public E getVal(){ return val; } public void setVal(E o){ val = o; } }