-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQueue_with_stack.py
More file actions
35 lines (25 loc) · 862 Bytes
/
Queue_with_stack.py
File metadata and controls
35 lines (25 loc) · 862 Bytes
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
from Stack.Stack import Stack
class QueueEmptyException(Exception):
pass
class Queue:
"""
An implementation of Queue with two Stacks
"""
def __init__(self):
self.__in_stack = Stack()
self.__out_stack = Stack()
def length(self):
return self.__in_stack.length() + self.__out_stack.length()
def enqueue(self, item):
self.__in_stack.push(item)
def is_empty(self):
return self.__out_stack.is_empty() and self.__in_stack.is_empty()
def dequeue(self):
if self.is_empty():
raise QueueEmptyException('Queue is empty')
if self.__out_stack.is_empty():
self._re_fill_out_stack()
return self.__out_stack.pop()
def _re_fill_out_stack(self):
while self.__in_stack.length():
self.__out_stack.push(self.__in_stack.pop())