Skip to content

Commit 1047709

Browse files
authored
Merge pull request #1755 from akgmage/dev
add queue using stack in python
2 parents 451343c + c7e323c commit 1047709

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Stacks/queue using stack.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Queue using stack
2+
class Queue:
3+
def __init__(self):
4+
self.enqueue_stack = [] # Stack for enqueue operations
5+
self.dequeue_stack = [] # Stack for dequeue operations
6+
7+
def enqueue(self, value):
8+
"""Enqueue: Add an element to the back of the queue."""
9+
self.enqueue_stack.append(value)
10+
11+
def dequeue(self):
12+
"""Dequeue: Remove and return the front element of the queue."""
13+
# If the dequeue stack is empty, transfer elements from the enqueue stack
14+
if not self.dequeue_stack:
15+
while self.enqueue_stack:
16+
# Pop an element from the enqueue stack and push it onto the dequeue stack
17+
element = self.enqueue_stack.pop()
18+
self.dequeue_stack.append(element)
19+
20+
# If the dequeue stack is still empty, the queue is empty
21+
if not self.dequeue_stack:
22+
raise IndexError("Queue is empty")
23+
24+
# Pop and return the front element from the dequeue stack
25+
return self.dequeue_stack.pop()
26+
27+
# Example usage
28+
queue = Queue()
29+
queue.enqueue(1)
30+
queue.enqueue(2)
31+
queue.enqueue(3)
32+
print(queue.dequeue()) # Output: 1
33+
print(queue.dequeue()) # Output: 2
34+
queue.enqueue(4)
35+
queue.enqueue(5)
36+
print(queue.dequeue()) # Output: 3
37+
print(queue.dequeue()) # Output: 4
38+
print(queue.dequeue()) # Output: 5

0 commit comments

Comments
 (0)