# LeetCode: Peeking Iterator Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * // This is the Iterator's API interface.3 * // You should not implement it, or speculate about its implementation.4 * function Iterator() {5 *    @ return {number}6 *    this.next = function() { // return the next number of the iterator7 *       ...8 *    };9 *10 *    @return {boolean}11 *    this.hasNext = function() { // return true if it still has numbers12 *       ...13 *    };14 * };15 */16
17/**18 * @param {Iterator} iterator19 */20var PeekingIterator = function (iterator) {21  this.stack = []22  while (iterator.hasNext()) {23    this.stack.unshift(iterator.next())24  }25}26
27/**28 * @return {number}29 */30PeekingIterator.prototype.peek = function () {31  return this.stack[this.stack.length - 1]32}33
34/**35 * @return {number}36 */37PeekingIterator.prototype.next = function () {38  return this.stack.pop()39}40
41/**42 * @return {boolean}43 */44PeekingIterator.prototype.hasNext = function () {45  return this.stack.length !== 046}47
48/**49 * Your PeekingIterator object will be instantiated and called as such:50 * var obj = new PeekingIterator(arr)51 * var param_1 = obj.peek()52 * var param_2 = obj.next()53 * var param_3 = obj.hasNext()54 */```

leetcode

## Next Post

LeetCode: Remove Element

Feb 8, 2021

Splice

Search Posts