Skip to content

Commit 330d57b

Browse files
committed
feat: added python solution of 232-implement-queue-using-stacks
1 parent 91f11b2 commit 330d57b

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

  • stack/232-implement-queue-using-stacks
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class Node:
2+
3+
def __init__(self, data):
4+
self.next = None
5+
self.data = data
6+
7+
8+
class MyQueue1:
9+
10+
def __init__(self):
11+
self.head = Node('#')
12+
self.tail = self.head
13+
14+
def push(self, data):
15+
self.tail.next = Node(data)
16+
self.tail = self.tail.next
17+
18+
def pop(self):
19+
val = self.head.next.data
20+
self.head.next.data = '#'
21+
self.head = self.head.next
22+
return val
23+
24+
def peek(self):
25+
return self.head.next.data
26+
27+
def empty(self):
28+
return self.head.next is None
29+
30+
31+
class MyQueue:
32+
33+
def __init__(self):
34+
self.in_stack, self.out_stack = [], []
35+
36+
def push(self, x: int) -> None:
37+
self.in_stack.append(x)
38+
39+
def pop(self) -> int:
40+
self.move()
41+
return self.out_stack.pop()
42+
43+
def peek(self) -> int:
44+
self.move()
45+
return self.out_stack[-1]
46+
47+
def empty(self) -> bool:
48+
return len(self.in_stack) == 0 and len(self.out_stack) == 0
49+
50+
def move(self) -> None:
51+
if not self.out_stack:
52+
while self.in_stack:
53+
self.out_stack.append(self.in_stack.pop())
54+
55+
56+
# Your MyQueue object will be instantiated and called as such:
57+
# obj = MyQueue()
58+
# obj.push(x)
59+
# param_2 = obj.pop()
60+
# param_3 = obj.peek()
61+
# param_4 = obj.empty()

0 commit comments

Comments
 (0)