forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue_using_stacks.py
More file actions
52 lines (42 loc) · 1.22 KB
/
Queue_using_stacks.py
File metadata and controls
52 lines (42 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#// Time Complexity : Amortised O(1), Worst case O(n)
#// Space Complexity : O(n)
#// Did this code successfully run on Leetcode : Yes
#// Any problem you faced while coding this : No
#// Your code here along with comments explaining your approach
# Use one in stock to push and other out stack to pop.
# When pop or peek is called, check if out stack is empty.
# If it is empty then pop all elements from in stack and push to out stack.
class MyQueue(object):
def __init__(self):
self.in_stack = []
self.out_stack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.in_stack.append(x)
def pop(self):
"""
:rtype: int
"""
self.peek()
return self.out_stack.pop()
def peek(self):
"""
:rtype: int
"""
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
return self.out_stack[-1]
def empty(self):
"""
:rtype: bool
"""
return not self.out_stack and not self.in_stack
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()