LeetCode: Implement Queue using Stacks Solution

Code speaks for itself

Implementation

1var MyQueue = function () {
2 this.s1 = []
3 this.s2 = []
4}
5
6MyQueue.prototype.push = function (x) {
7 while (this.s1.length) {
8 this.s2.push(this.s1.pop())
9 }
10 this.s1.push(x)
11 while (this.s2.length) {
12 this.s1.push(this.s2.pop())
13 }
14}
15
16MyQueue.prototype.pop = function () {
17 return this.s1.pop()
18}
19
20MyQueue.prototype.peek = function () {
21 return this.s1.slice(-1)[0]
22}
23
24MyQueue.prototype.empty = function () {
25 return !this.s1.length && !this.s2.length
26}

References

Original problem

Similar problems

Implement Stack using Queues

Comments

Loading comments...

Tags

leetcode

stack

queue

Next Post

LeetCode: Symmetric Tree

Recursion

Previous Post

CodeWars: Recover a secret string from random triplets

It's easy to make thing more complicated

HoningJS

Search Posts