LeetCode: Peeking Iterator Solution

1/**
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 iterator
7 * ...
8 * };
9 *
10 * @return {boolean}
11 * this.hasNext = function() { // return true if it still has numbers
12 * ...
13 * };
14 * };
15 */
16
17/**
18 * @param {Iterator} iterator
19 */
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 !== 0
46}
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 */

Comments

Loading comments...

Tags

leetcode

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Remove Element

Splice

HoningJS

Search Posts