Skip to content

Commit bfea4ce

Browse files
authored
Queue_using_Stacks
Queue using two stacks Create two stacks and pop the elements from stack 1 and print the pop elements into stack 2. Finally pop the stack2 elements then we get the elements of pop elements as queue elements
1 parent 5d2e716 commit bfea4ce

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Queue_using_Stacks

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class QueueUsingTwoStacks:
2+
def __init__(self):
3+
#stack for enqueue operation
4+
self.stack1=[]
5+
#stack for dequeue operation
6+
self.stack2=[]
7+
def enqueue(self,item):
8+
#append the items into stack1
9+
self.stack1.append(item)
10+
def dequeue(self):
11+
#check if stack2 is empty or not
12+
if not self.stack2:
13+
#if stack2 is empty go to stack1
14+
while self.stack1:
15+
#append the pop items of stack1 into stack2
16+
self.stack2.append(self.stack1.pop())
17+
if not self.stack2:
18+
raise IndexError("Dequeue from an empty stack")
19+
return self.stack2.pop()
20+
queue=QueueUsingTwoStacks()
21+
queue.enqueue(1)
22+
queue.enqueue(2)
23+
print(queue.dequeue())
24+
queue.enqueue(3)
25+
print(queue.dequeue())
26+
print(queue.dequeue())

0 commit comments

Comments
 (0)