LeetCode: Implement Queue using Stacks Solution
Code speaks for itselfImplementation
1var MyQueue = function () {2 this.s1 = []3 this.s2 = []4}56MyQueue.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}1516MyQueue.prototype.pop = function () {17 return this.s1.pop()18}1920MyQueue.prototype.peek = function () {21 return this.s1.slice(-1)[0]22}2324MyQueue.prototype.empty = function () {25 return !this.s1.length && !this.s2.length26}
References
Similar problems
Implement Stack using Queues
Comments
Loading comments...
Tags
leetcode
stack
queue
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: Symmetric Tree
Recursion
Previous Post
CodeWars: Recover a secret string from random triplets
It's easy to make thing more complicated