File tree 1 file changed +10
-7
lines changed
0232-implement-queue-using-stacks
1 file changed +10
-7
lines changed Original file line number Diff line number Diff line change 2
2
var MyQueue = function ( ) {
3
3
this . storage = [ ] ;
4
4
this . start = 0 ;
5
- this . tail = 0 ;
6
5
} ;
7
6
8
7
/**
@@ -11,16 +10,20 @@ var MyQueue = function() {
11
10
*/
12
11
MyQueue . prototype . push = function ( x ) {
13
12
this . storage . push ( x ) ;
14
- this . tail ++ ;
15
13
} ;
16
14
17
15
/**
18
16
* @return {number }
19
17
*/
20
18
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
+ }
24
27
return val ;
25
28
26
29
} ;
@@ -29,7 +32,7 @@ MyQueue.prototype.pop = function() {
29
32
* @return {number }
30
33
*/
31
34
MyQueue . prototype . peek = function ( ) {
32
- if ( this . storage . legnth === 0 ) return ;
35
+ if ( this . empty ( ) ) return null ;
33
36
let val = this . storage [ this . start ] ;
34
37
return val ;
35
38
} ;
@@ -38,7 +41,7 @@ MyQueue.prototype.peek = function() {
38
41
* @return {boolean }
39
42
*/
40
43
MyQueue . prototype . empty = function ( ) {
41
- return this . storage . length === 0 ;
44
+ return this . start >= this . storage . length ;
42
45
} ;
43
46
44
47
/**
You can’t perform that action at this time.
0 commit comments