Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit29df8e9

Browse files
authored
Merge pull requestneetcode-gh#2113 from nikkikharkwal/main
Create: 0232-implement-queue-using-stacks.js
2 parentsa7c9bf7 +9353535 commit29df8e9

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// https://leetcode.com/problems/implement-queue-using-stacks/
2+
3+
varMyQueue=function(){
4+
this.stack1=[];
5+
this.stack2=[];
6+
};
7+
8+
/**
9+
*@param {number} x
10+
*@return {void}
11+
*/
12+
MyQueue.prototype.push=function(x){
13+
this.stack1.push(x);
14+
};
15+
16+
/**
17+
*@return {number}
18+
*/
19+
MyQueue.prototype.pop=function(){
20+
this.swappingStacks();
21+
22+
if(!this.stack2.length){
23+
returnnull;
24+
}
25+
returnthis.stack2.pop();
26+
};
27+
28+
/**
29+
*@return {number}
30+
*/
31+
MyQueue.prototype.peek=function(){
32+
this.swappingStacks();
33+
returnthis.stack2.length==0 ?null :this.stack2[this.stack2.length-1]
34+
};
35+
36+
/**
37+
*@return {boolean}
38+
*/
39+
MyQueue.prototype.empty=function(){
40+
returnthis.stack1.length===0&&this.stack2.length===0;
41+
};
42+
43+
MyQueue.prototype.swappingStacks=function(){
44+
if(this.stack1.length){
45+
this.stack2=[...this.stack1.reverse(), ...this.stack2];
46+
this.stack1=[];
47+
}
48+
}
49+
50+
/**
51+
* Your MyQueue object will be instantiated and called as such:
52+
* var obj = new MyQueue()
53+
* obj.push(x)
54+
* var param_2 = obj.pop()
55+
* var param_3 = obj.peek()
56+
* var param_4 = obj.empty()
57+
*/

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp