Skip to content

Commit 6771bbf

Browse files
committed
Time: 0 ms (100%), Space: 48.9 MB (49.86%) - LeetHub
1 parent b2bc6ad commit 6771bbf

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

0232-implement-queue-using-stacks/0232-implement-queue-using-stacks.js

+10-7
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
var MyQueue = function() {
33
this.storage = [];
44
this.start = 0;
5-
this.tail = 0;
65
};
76

87
/**
@@ -11,16 +10,20 @@ var MyQueue = function() {
1110
*/
1211
MyQueue.prototype.push = function(x) {
1312
this.storage.push(x);
14-
this.tail++;
1513
};
1614

1715
/**
1816
* @return {number}
1917
*/
2018
MyQueue.prototype.pop = function() {
21-
if (this.storage.length === 0) return;
22-
let val = this.storage.shift();
23-
this.tail--;
19+
if (this.empty()) return null;
20+
const val = this.storage[this.start];
21+
this.start++;
22+
23+
if(this.start > this.storage.length/2) {
24+
this.storage = this.storage.slice(this.start);
25+
this.start = 0;
26+
}
2427
return val;
2528

2629
};
@@ -29,7 +32,7 @@ MyQueue.prototype.pop = function() {
2932
* @return {number}
3033
*/
3134
MyQueue.prototype.peek = function() {
32-
if(this.storage.legnth === 0) return;
35+
if (this.empty()) return null;
3336
let val = this.storage[this.start];
3437
return val;
3538
};
@@ -38,7 +41,7 @@ MyQueue.prototype.peek = function() {
3841
* @return {boolean}
3942
*/
4043
MyQueue.prototype.empty = function() {
41-
return this.storage.length === 0;
44+
return this.start >= this.storage.length;
4245
};
4346

4447
/**

0 commit comments

Comments
 (0)