forked from codehouseindia/Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackusingQueue.py
66 lines (50 loc) · 1.1 KB
/
StackusingQueue.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
# Program to implement a stack using
# two queue
from queue import Queue
class Stack:
def __init__(self):
# Two inbuilt queues
self.q1 = Queue()
self.q2 = Queue()
# To maintain current number
# of elements
self.curr_size = 0
def push(self, x):
self.curr_size += 1
# Push x first in empty q2
self.q2.put(x)
# Push all the remaining
# elements in q1 to q2.
while (not self.q1.empty()):
self.q2.put(self.q1.queue[0])
self.q1.get()
# swap the names of two queues
self.q = self.q1
self.q1 = self.q2
self.q2 = self.q
def pop(self):
# if no elements are there in q1
if (self.q1.empty()):
return
self.q1.get()
self.curr_size -= 1
def top(self):
if (self.q1.empty()):
return -1
return self.q1.queue[0]
def size(self):
return self.curr_size
# Driver Code
if __name__ == '__main__':
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print("current size: ", s.size())
print(s.top())
s.pop()
print(s.top())
s.pop()
print(s.top())
print("current size: ", s.size())
# This code is contributed by PranchalK