import java.util.Iterator;
class MyLinkedList<E> {
    Node<E> head;
  
    public void addFirst(E x){
	head = new Node<E>(x,head);
    }
    public void add(E x){
	if (head == null){
	    head = new Node<E>(x);
	} else {
	    Node<E> pre,curr;
	    pre = curr = head;
	    while (curr != null){
		pre = curr;
		curr = curr.getNext();
	    }
	    pre.setNext(new Node<E>(x));
	}
    }

    class MyLinkedListIterator<E> implements Iterator<E> {
	Node<E> curNode;
	public MyLinkedListIterator(MyLinkedList<E> 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<E> iterator(){
	return new MyLinkedListIterator<E>(this);
    }
  
    public void print(){
	Iterator<E> it = iterator();
        while (it.hasNext()){
	    E e = it.next();
	    System.out.print(e+" ");
	}
	System.out.println();
    }

    public static void main(String[] args){
	MyLinkedList<Integer> lst = new MyLinkedList<Integer>();
	lst.add(2); lst.add(3); lst.addFirst(1);
	lst.print();
    }
}

class Node<E> {
    E val;
    Node<E> next;
    public Node(E x, Node<E> next){
	val = x;
	this.next = next;
    }
    public Node(E x){
	this(x,null);
    }
    public void setNext(Node<E> next){
	this.next = next;
    }
    public Node<E> getNext(){
	return this.next;
    }

    public E getVal(){
	return val;
    }

    public void setVal(E o){
	val = o;
    }
}


