File tree 1 file changed +48
-0
lines changed
Queue/Implementation of Queue using Stack
1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ class MyQueue :
2
+
3
+ def __init__ (self ):
4
+ # queue is implemented by using 2 stacks
5
+ self .s1 = [] # stack-1
6
+ self .s2 = [] # stack-2
7
+
8
+
9
+
10
+ def push (self , x : int ) -> None :
11
+ # Move all elements from s1 to s2
12
+ while len (self .s1 )!= 0 :
13
+ self .s2 .append (self .s1 [- 1 ])
14
+ self .s1 .pop ()
15
+
16
+ # Push item into self.s1
17
+ self .s1 .append (x )
18
+
19
+ # Push everything back to s1
20
+ while len (self .s2 ) != 0 :
21
+ self .s1 .append (self .s2 [- 1 ])
22
+ self .s2 .pop ()
23
+
24
+
25
+
26
+ def pop (self ) -> int :
27
+ # Return top of self.s1
28
+ return self .s1 .pop ()
29
+
30
+
31
+ def peek (self ) -> int :
32
+ return self .s1 [- 1 ]
33
+
34
+
35
+
36
+ def empty (self ) -> bool :
37
+ if self .s1 :
38
+ return False
39
+ return True
40
+
41
+
42
+
43
+ # Your MyQueue object will be instantiated and called as such:
44
+ # obj = MyQueue()
45
+ # obj.push(x)
46
+ # param_2 = obj.pop()
47
+ # param_3 = obj.peek()
48
+ # param_4 = obj.empty()
You can’t perform that action at this time.
0 commit comments