-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack using Queue.py
More file actions
57 lines (46 loc) · 1.39 KB
/
Stack using Queue.py
File metadata and controls
57 lines (46 loc) · 1.39 KB
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
'''##Description
Complete the function of push and pop and top for a stack, queue object names are Q1 and Q2.
Expected Time complexity is O(N) for push and O(1) for pop and top.
#Input Description
This is a function complete problem. You just have to complete the function. The input format given below is just for your understanding.
The first line of the input contains Q, the number of queries to be executed.
Each query X is of type X = 0, X = 1 or X = 2.
Query X = 0 indicates, an element Y to be pushed into the stack.
Query X = 2 indicates, an element to be popped off the stack.
Query X = 1 indicates, an element to be peeked from the stack.
#Output Description
For each query of type X = 1, print the value at the front of the queue, and for X = 2 print the popped value.
##Sample Input 1
6
0 1
0 2
0 3
1
2
1
##Sample Output 1
3
3
2
##Solution-'''
class Stack:
def __init__(self):
self.Q1 = []
self.Q2 = []
def push(self, value):
self.Q2.append(value)
while self.Q1:
self.Q2.append(self.Q1.pop(0))
self.Q1,self.Q2=self.Q2,self.Q1
def pop(self):
if not self.isEmpty():
print(self.Q1.pop(0))
else:
print(-1)
def top(self):
if not self.isEmpty():
print(self.Q1[0])
else:
print(-1)
def isEmpty(self):
return len(self.Q1)==0