www.pudn.com > campusleader.rar > LinkedListWithIterator.java, change:2012-01-04,size:1435b


package GraphPackage; 
 
import java.util.Iterator; 
import java.util.NoSuchElementException; 
 
public class LinkedListWithIterator<T> implements ListWithIteratorInterface<T> { 
	 
	private Node firstNode; 
	private Node lastNode; 
	private int length; 
	 
	public LinkedListWithIterator(){ 
		clear(); 
	} 
	 
	public final void clear(){ 
		firstNode = null; 
		length = 0; 
	} 
	public boolean isEmpty(){ 
		return firstNode == null; 
	} 
	 
	public void add(T newEntry){ 
		Node newNode = new Node(newEntry); 
		if (isEmpty()){ 
			firstNode = newNode; 
			lastNode =newNode; 
		} 
		else{ 
			lastNode.next = newNode; 
			lastNode = lastNode.next; 
		} 
	}  
	public Iterator<T> getIterator() { 
		return new IteratorForLinkedList(); 
	} 
	 
	private class IteratorForLinkedList implements Iterator<T>{ 
		private Node curruntNode; 
		private Node nextNode; 
		 
		private IteratorForLinkedList(){ 
			curruntNode = firstNode; 
		} 
		 
		public boolean hasNext(){ 
			if(curruntNode==null) 
			{ 
				return false; 
			} 
			return curruntNode!=null; 
		} 
		public T next(){ 
			if (hasNext()){ 
				nextNode = curruntNode; 
				curruntNode = curruntNode.next; 
				return nextNode.data; 
			} 
			else 
				return null; 
		} 
		public void remove(){ 
			 
		} 
	} 
	 
	private class Node{ 
		private T data; 
		private Node next; 
		 
		private Node(T dataPortion){ 
			data = dataPortion; 
			next = null; 
		} 
		 
	} 
	 
}