-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapple_Implement_Queue_Using_Two_Stacks.py
More file actions
42 lines (35 loc) · 1.05 KB
/
apple_Implement_Queue_Using_Two_Stacks.py
File metadata and controls
42 lines (35 loc) · 1.05 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
#This problem was asked by Apple.
#Implement a queue using two stacks.
# Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue,
# which removes it.
# Solution:
class Queue:
def __init__(self):
self.main_stack = list()
self.aux_stack = list()
def __repr__(self):
return str(self.main_stack)
def enqueue(self, val):
self.main_stack.append(val)
def dequeue(self):
if not self.main_stack:
return None
while self.main_stack:
self.aux_stack.append(self.main_stack.pop())
val = self.aux_stack.pop()
while self.aux_stack:
self.main_stack.append(self.aux_stack.pop())
return val
q = Queue()
q.enqueue(1)
assert q.main_stack == [1]
q.enqueue(2)
assert q.main_stack == [1, 2]
q.enqueue(3)
assert q.main_stack == [1, 2, 3]
val = q.dequeue()
assert val == 1
assert q.main_stack == [2, 3]
val = q.dequeue()
assert val == 2
assert q.main_stack == [3]