LeetCode 284 - Peeking Iterator

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a247027417/article/details/83473862

284. Peeking Iterator
Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation — it essentially peek() at the element that will be returned by the next call to next().

Example:

Assume that the iterator is initialized to the beginning of the list: [1,2,3].

Call next() gets you 1, the first element in the list.
Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. 
You call next() the final time and it returns 3, the last element. 
Calling hasNext() after that should return false.
Follow up: How would you extend your design to be generic and work with all types, not just integer?

给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。

示例:

假设迭代器被初始化为列表 [1,2,3]。

调用 next() 返回 1,得到列表中的第一个元素。
现在调用 peek() 返回 2,下一个元素。在此之后调用 next() 仍然返回 2。
最后一次调用 next() 返回 3,末尾元素。在此之后调用 hasNext() 应该返回 false。

【思路】

整道题的意思是:peek取得的是next()的后面一个元素,如果不对next进行修改,那么在使用了peek之后再使用next取得的将会是next的后面一个字符。因此我们需要修改next函数,如果已经使用了peek,那么在next函数中,我们需要做的是取出现在指针指向的值而不是下一个值。因此我们使用一个指示是否使用了peek的指示值,使用一个缓存变量returnNum,如果使用了peek方法,那么我们会在returnNum中存入此时的iterator.next()的值,这个时候如果再使用next方法,不会执行.next()语句,直接将缓存变量返回即可。当使用hasNext()函数时,如果当使用了peek函数,此时指针已经往后走了一个,但是并没有执行next,可能会出现还没有到达最后一个值,但hasNext函数返回的false;因此hasNext的值需要保证没有使用peek,而且iterator.next==false;

【代码】

class PeekingIterator implements Iterator<Integer> {
	
	Iterator<Integer> iterator;
	boolean flag ;
	Integer returnNum;
	
	public PeekingIterator(Iterator<Integer> iterator) {
	    this.iterator = iterator;
	    this.flag = false;
	    this.returnNum = null;
	}

 // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
		if(!this.flag)
		{
			this.returnNum = this.iterator.next();
			this.flag = true;
		}
		return this.returnNum;
	}

	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
	    if(!this.flag)
	    	return this.iterator.next();
	    Integer returnNum = this.returnNum;
	    this.returnNum = null;
	    this.flag = false;
	    return returnNum;
	}

	@Override
	public boolean hasNext() {
	    return (this.flag || this.iterator.hasNext()); 
	}
}

猜你喜欢

转载自blog.csdn.net/a247027417/article/details/83473862