0%

Design Stack and Queue

Implement Stack using Queue

lc225 Implement Stack using Queues ($\leftarrow$ click)
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement a last-in-first-out (LIFO) stack using only one queue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class MyStack:
def __init__(self):
self.que = collections.deque()

def push(self,x):
# T(n) = O(N), S(n) = S(N)
n = len(self.que)
self.que.append(x)
for _ in range(n):
self.que.append(self.que.popleft())

def pop(self):
# T(n) = O(1), S(n) = S(N)
return self.que.popleft()

def top(self):
# T(n) = O(1), S(n) = S(N)
return self.que[0]

def empty(self):
# T(n) = O(1), S(n) = S(N)
return not self.que

Implement Queue using Stacks

lc 232 Implement Queue using Stacks ($\leftarrow$ click)
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

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
class MyQueue:

def __init__(self):
self.stIn = []
self.stOut = []

def push(self,x):
# T(n) = O(1), S(n) = S(N)
self.stIn.append(x)

def pop(self):
# amortized T(n) = O(1), S(n) = S(N)
top = self.peek() # have to call self.peek() to modify self.stOut first.
self.stOut.pop()
return top

def peek(self):
# amortized T(n) = O(1), S(n) = S(N)
if self.stOut: return self.stOut[-1]
if not self.stIn: return -1
while self.stIn:
self.stOut.append(self.stIn.pop())
return self.stOut[-1]

def isEmpty(self):
# T(n) = O(1), S(n) = S(N)
return not self.stIn and not self.stOut

Note: The peek() and pop() functions require a total reversal of N elements in N consecutive front element deletion operations, leading to an amortized time complexity of O(1).

-------------End of blogThanks for your reading-------------