public Iterator<T> iterator(){
	
	return new MyIterator();
}

private class MyIterator implements Iterator<T>{
	
	private Node<T> nextnode;
	
	public MyIterator() {
		nextnode = head;
	}
	
	public boolean hasNext() {
		return (nextnode != null);
	}
	public T next() {
		if(nextnode == null) {
			throw new NoSuchElementException();
		}
		
		T val = nextnode.data;
		nextnode = nextnode.next;
		return val;
	}
	public void remove() {
		
	}
}

기존 MySingleLinkedList 클래스에 이너클래스로 

MyIterator를 만들어주었다.

 

Node객체를 멤버로 가지고

 

생성자에서 head값을 넣어주고

 

다음 노드가 있는지 확인하는 메서드와

 

다임 노드의 데이터를 반환하는 메서드를 구현하였다.

+ Recent posts