forked from someshgkale123/LeetCode-Easy
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Implement Queue using Stacks
44 lines (34 loc) · 963 Bytes
/
Implement Queue using Stacks
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
Problem Statement:
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
Solution:
class MyQueue(object):
def __init__(self):
self.li=[]
def push(self, x):
if self.li:
self.li.insert(0,x)
else:
self.li.append(x)
def pop(self):
return self.li.pop()
def peek(self):
return self.li[-1]
def empty(self):
return len(self.li)==0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()