File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://leetcode.com/problems/implement-queue-using-stacks/
2+
3+ var MyQueue = 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+ return null ;
24+ }
25+ return this . stack2 . pop ( ) ;
26+ } ;
27+
28+ /**
29+ * @return {number }
30+ */
31+ MyQueue . prototype . peek = function ( ) {
32+ this . swappingStacks ( ) ;
33+ return this . stack2 . length == 0 ? null : this . stack2 [ this . stack2 . length - 1 ]
34+ } ;
35+
36+ /**
37+ * @return {boolean }
38+ */
39+ MyQueue . prototype . empty = function ( ) {
40+ return this . 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+ */
You can’t perform that action at this time.
0 commit comments