From 491c2dee55bdc9575dc5a52965a78348937685b6 Mon Sep 17 00:00:00 2001 From: Jinyoung Jeong <80400463+jyoung2419@users.noreply.github.com> Date: Sat, 19 Sep 2026 22:58:26 +0900 Subject: [PATCH] Implement PeekingIterator for iterator functionality --- .../284. Peeking Iterator" | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 "leetcode3/\354\240\225\354\247\204\354\230\201/284. Peeking Iterator" diff --git "a/leetcode3/\354\240\225\354\247\204\354\230\201/284. Peeking Iterator" "b/leetcode3/\354\240\225\354\247\204\354\230\201/284. Peeking Iterator" new file mode 100644 index 00000000..bb2cf35f --- /dev/null +++ "b/leetcode3/\354\240\225\354\247\204\354\230\201/284. Peeking Iterator" @@ -0,0 +1,56 @@ +/** + * // This is the Iterator's API interface. + * // You should not implement it, or speculate about its implementation. + * function Iterator() { + * @ return {number} + * this.next = function() { // return the next number of the iterator + * ... + * }; + * + * @return {boolean} + * this.hasNext = function() { // return true if it still has numbers + * ... + * }; + * }; + */ + +/** + * @param {Iterator} iterator + */ +var PeekingIterator = function(iterator) { + this.iterator = iterator; + + this.nextValue = iterator.hasNext() ? iterator.next() : null; +}; + +/** + * @return {number} + */ +PeekingIterator.prototype.peek = function() { + return this.nextValue; +}; + +/** + * @return {number} + */ +PeekingIterator.prototype.next = function() { + const ans = this.nextValue; + + this.nextValue = this.iterator.hasNext() ? this.iterator.next() : null; + return ans; +}; + +/** + * @return {boolean} + */ +PeekingIterator.prototype.hasNext = function() { + return this.nextValue !== null; +}; + +/** + * Your PeekingIterator object will be instantiated and called as such: + * var obj = new PeekingIterator(arr) + * var param_1 = obj.peek() + * var param_2 = obj.next() + * var param_3 = obj.hasNext() + */