/* A singly linked list implementation, used similar to Java's LinkedList class.
 * Methods currently supported:
 * new LinkedList() - creates an empty linked list.
 * add(item) - adds item to the list.
 * iterator() - return a iterator object that traverses the list in the reverse
 * order to that which the items were added.
 * next() (on iterator object) - returns the next item in the list and advances
 * the iteration.
 * hasNext() (on iterator object) - returns true if there are more elements to
 * come in the list traveral, or false otherwise.
 *
 * Copyright (C) Colours of Spain 2006
*/
function LinkedList() {
		// List head.
		this.head=null;
		
		// Begin list node class.
		function LinkedList_Node(item, nextItem) {
			// Data part
	    this.data = item;
	    // Next pointer
	    this.next = nextItem;
	  } // end LinkedList_Node class.
    
    //Add an item to the end of the list.
    LinkedList.prototype.add= function (item) {
    	var oldHead=this.head;
    	this.head=new LinkedList_Node(item, oldHead);
    }
		
		//Begin list iterator class.
		function LinkedList_Iterator(head) {
			var position=head;
			
			LinkedList_Iterator.prototype.next= function () {
				if (position!=null) {
					var value=position.data;
					position=position.next;
					return value;
				} else {
					throw new NoSuchElementException();
				}
			}
			
			LinkedList_Iterator.prototype.hasNext= function () {
				return (position!=null);
			}
			
		} //end LinkedList_Iterator class.

		//Iterate over the list.
		LinkedList.prototype.iterator= function () {
			return new LinkedList_Iterator(this.head);
		}
    
} // end LinkedList class.

