Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2113 from nikkikharkwal/main
Browse files Browse the repository at this point in the history
Create: 0232-implement-queue-using-stacks.js
  • Loading branch information
saip7795 authored Jan 21, 2023
2 parents a7c9bf7 + 9353535 commit 29df8e9
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions javascript/0232-implement-queue-using-stacks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// https://leetcode.com/problems/implement-queue-using-stacks/

var MyQueue = function() {
this.stack1 = [];
this.stack2 = [];
};

/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stack1.push(x);
};

/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
this.swappingStacks();

if(!this.stack2.length){
return null;
}
return this.stack2.pop();
};

/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
this.swappingStacks();
return this.stack2.length == 0 ? null : this.stack2[this.stack2.length-1]
};

/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.stack1.length === 0 && this.stack2.length === 0;
};

MyQueue.prototype.swappingStacks = function() {
if (this.stack1.length) {
this.stack2 = [...this.stack1.reverse(), ...this.stack2];
this.stack1 = [];
}
}

/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/

0 comments on commit 29df8e9

Please sign in to comment.