선형데이터구조, 연결리스트(LinkedList) #7 반복자(Iterator)

2021. 12. 13. 13:10DataStructure

이전글

https://yonghwankim-dev.tistory.com/183

 

선형데이터구조, 연결리스트(LinkedList) #6 peekFirst & peekLast 메서드

이전글 https://yonghwankim-dev.tistory.com/182 선형데이터구조, 연결리스트(LinkedList) #5 remove & find 메서드 이전글 https://yonghwankim-dev.tistory.com/181 선형데이터구조, 연결리스트(LinkedList) #4..

yonghwankim-dev.tistory.com

 

개요

이전글에서는 peekFirst, peekLast 메서드를 구현하였습니다. 이번글에서는 LinkedList 클래스의 반복자(Iterator) 내부 클래스를 구현하겠습니다.

 

1. 반복자(Iterator)

일반적으로 배열의 각각의 원소를 출력할 때 다음과 같이 코드를 작성할 수 있습니다.

int[] arr = {1,2,3,4,5};
for(int i=0; i<arr.length; i++){
	System.out.println(arr[i]);
}

혹은 다음과 같이 작성할 수 있습니다.

int[] arr = {1,2,3,4,5};

for(int x : arr){
	System.out.println(x);
}

하지만 객체에서 두번째 방식으로 반복문이 동작하도록 하기 위해서는 Iterator 인터페이스를 구현해야 합니다.

 

2. Iterator 인터페이스 구현

Iterator 인터페이스를 구현하는 IteratorHelper 클래스의 구현은 다음과 같습니다.

// Iterator 인터페이스를 구현하는 클래스를 만드는 메서드
public Iterator<E> iterator(){
	return new IteratorHelper();
}

class IteratorHelper implements Iterator<E>{
		Node<E> index;
			
		public IteratorHelper() {
			index = head;
		}

		// 임시 포인터(index)가 null을 가리키는지 여부 확인
		@Override
		public boolean hasNext() {
			return (index!=null);
		}

		// index가 가리키는 노드의 데이터값을 반환 및 노드 이동
		@Override
		public E next() {
			if(!hasNext())
			{
				throw new NoSuchElementException();
			}
			E val = index.data;
			index = index.next;
			return val;
		}
		
	}
	@Test
	void iteratorTest() {
		LinkedList<String> list = new LinkedList<String>();
		
		list.addFirst("A");
		list.addFirst("B");
		list.addFirst("C");
		
		Iterator<String> itor = list.iterator(); 
		while(itor.hasNext())
		{
			System.out.print(itor.next()+" ");	// Expected Output : C B A
		}
	}
C B A

 

References

[부스트코스] 자바로 구현하고 배우는 자료구조