알고리즘 공부

284. Peeking Iterator java 풀이

철매존 2026. 8. 2. 18:02
728x90
반응형

이게 왜 미디엄..? 이라는 생각이 들정도로 다른 것들이랑 차이가 많이 나는 문제이다.

솔직히 풀이랄것도 없다. 그냥 맨 위 값을 캐싱하면 해결된다.

 

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html


class PeekingIterator implements Iterator<Integer> {
    Iterator<Integer> iterator;
    Integer cache;

	public PeekingIterator(Iterator<Integer> iterator) {
        this.iterator = iterator;
        cache = iterator.next();
	}
	
    // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
        return cache;
	}
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
        // 맨 위 값을 보관해두고 보내준다.
        if(cache == null) {
            cache = iterator.next();
            return cache;
        } else {
            // 캐시 값이 있다면? 바꿔주고 보내준다.
            int returner = cache;
            
            // 다음 값이 있다면 그 값을 저장하고 보내주기.
            if(iterator.hasNext()) {
                cache = iterator.next();
            } else {
                cache = null; // 없으면 null
            }
            return returner;
        }
	}
	
	@Override
	public boolean hasNext() {
	    return null != cache;
	}
}
반응형