Skip to content

added implementing stack using two queues #10075

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions data_structures/stacks/stack_using_two_queues.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# for explanation refer this https://www.geeksforgeeks.org/implement-stack-using-queue/

class StackWithQueues:
def __init__(self):
self.queue1 = []
self.queue2 = []

def push(self, element):
self.queue1.append(element)

def pop(self):
if not self.queue1:
return None

while len(self.queue1) > 1:
self.queue2.append(self.queue1.pop(0))

element = self.queue1.pop(0)

self.queue1, self.queue2 = self.queue2, self.queue1

return element

def peek(self):
if not self.queue1:
return None

while len(self.queue1) > 1:
self.queue2.append(self.queue1.pop(0))

element = self.queue1[0]

self.queue2.append(self.queue1.pop(0))

self.queue1, self.queue2 = self.queue2, self.queue1

return element


# Initialize the stack
stack = StackWithQueues()

while True:
print("\nChoose operation:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Quit")

choice = input("Enter choice (1/2/3/4): ")

if choice == '1':
element = input("Enter element to push: ")
stack.push(element)
print(f"{element} pushed onto the stack.")
elif choice == '2':
popped_element = stack.pop()
if popped_element is not None:
print(f"Popped element: {popped_element}")
else:
print("Stack is empty.")
elif choice == '3':
peeked_element = stack.peek()
if peeked_element is not None:
print(f"Top element: {peeked_element}")
else:
print("Stack is empty.")
elif choice == '4':
break
else:
print("Invalid choice. Please try again.")