标签:
原题链接在这里:https://leetcode.com/problems/peeking-iterator/
设计一个是否被peek过得flag, isPeeked with initialization as false.
同时保存peek过得值peekVal. 若果isPeeked == true 已经peek过,next()直接返回peekVal, hasNext()直接看isPeek为true 就返回 true.
AC Java:
1 // Java Iterator interface reference: 2 // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html 3 class PeekingIterator implements Iterator<Integer> { 4 Iterator<Integer> it; 5 boolean isPeeked = false; 6 Integer peekVal = null; 7 8 public PeekingIterator(Iterator<Integer> iterator) { 9 // initialize any member here. 10 this.it = iterator; 11 } 12 13 // Returns the next element in the iteration without advancing the iterator. 14 public Integer peek() { 15 if(!isPeeked){ 16 isPeeked = true; 17 peekVal = it.next(); 18 } 19 return peekVal; 20 } 21 22 // hasNext() and next() should behave the same as in the Iterator interface. 23 // Override them if needed. 24 @Override 25 public Integer next() { 26 if(!isPeeked){ 27 return it.next(); 28 } 29 isPeeked = false; 30 return peekVal; 31 } 32 33 @Override 34 public boolean hasNext() { 35 return isPeeked || it.hasNext(); 36 } 37 }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4919604.html