-
Notifications
You must be signed in to change notification settings - Fork 39
/
stack_two_queues.py
67 lines (41 loc) · 1.51 KB
/
stack_two_queues.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from typing import Any, List
class Queue:
def __init__(self) -> None:
self.queue:List[Any] = []
def size(self) -> int:
return len(self.queue)
def is_empty(self) -> bool:
return len(self.queue) == 0
def enqueue(self, item:Any) -> None:
self.queue.insert(0, item)
def dequeue(self) -> Any:
if self.is_empty():
raise Exception('Queue is empty')
return self.queue.pop()
class Stack:
def __init__(self):
self.input: Queue = Queue()
self.output:Queue = Queue()
def push(self, x: Any) -> None:
self.input.enqueue(x)
def pop(self) -> Any:
if self.input.is_empty():
raise Exception('Queue is empty')
while self.input.size() > 1:
self.output.enqueue(self.input.dequeue())
item:Any = self.input.dequeue()
while not self.output.is_empty():
self.input.enqueue(self.output.dequeue())
return item
def peek(self) -> Any:
if self.input.is_empty():
raise Exception('Queue is empty')
while self.input.size() > 1:
self.output.enqueue(self.input.dequeue())
item:Any = self.input.dequeue()
self.output.enqueue(item)
while not self.output.is_empty():
self.input.enqueue(self.output.dequeue())
return item
def is_empty(self) -> bool:
return self.input.is_empty()