-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue using Stack.py
More file actions
58 lines (48 loc) · 1.43 KB
/
Queue using Stack.py
File metadata and controls
58 lines (48 loc) · 1.43 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 front for a queue, stack object names are S1 and S2.
Expected Time complexity is O(N) for push and O(1) for pop and front.
#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 queue.
Query X = 2 indicates, an element to be removed from the queue.
Query X = 1 indicates, an element to be peeked from the queue.
#Output Description
For each query of type X = 1, print the value at the front of the queue.
##Sample Input 1
6
0 1
0 2
0 3
1
2
1
##Sample Output 1
1
2
##Solution-'''
class Queue:
def __init__(self):
self.s1 = []
self.s2 = []
def enqueue(self, value):
# add element
self.s1.append(value)
def dequeue(self):
# Pop and return top element
if not self.s2:
while self.s1:
self.s2.append(self.s1.pop())
if not self.s2:
return None
return self.s2.pop()
def peek(self):
if not self.s2:
while self.s1:
self.s2.append(self.s1.pop())
if not self.s2:
return None
return self.s2[-1]
def isEmpty(self):
return len(self.s1)==0 or len(self.s2)==0