forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_using_two_queues.py
91 lines (71 loc) · 1.99 KB
/
stack_using_two_queues.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# 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
"""
>>> stack = StackWithQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.push(3)
>>> stack.peek()
3
>>> stack.pop()
3
>>> stack.peek()
2
>>> stack.pop()
2
>>> stack.pop()
1
>>> stack.peek() is None
True
"""
# 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.")