forked from priyankchheda/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue_using_stack.py
53 lines (43 loc) · 1.24 KB
/
queue_using_stack.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
"""
Problem Statement:
We are given a stack data structure with push and pop operations, the task is
to implement a queue using instances of stack data structure and operations
on them.
URL: https://www.geeksforgeeks.org/queue-using-stacks/
"""
class Queue:
""" Queue implementation using two Stacks """
def __init__(self):
self.stack = []
self.aux_stack = []
def enqueue(self, element):
""" enqueue element to queue """
while self.stack:
self.aux_stack.append(self.stack.pop())
self.aux_stack.append(element)
while self.aux_stack:
self.stack.append(self.aux_stack.pop())
def dequeue(self):
""" dequeue element to queue """
if not self.stack:
raise IndexError("queue is empty")
return self.stack.pop()
def main():
""" operational function """
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
queue.enqueue(4)
queue.enqueue(5)
print(queue.dequeue())
print(queue.dequeue())
try:
print(queue.dequeue())
except IndexError as err:
print(err)
if __name__ == '__main__':
main()