Implement Stack using Queues
LeetCode 225 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Rotate after each push so the newest is at the front.
நான் Implement Stack using Queues (LeetCode 225) ஐ இப்படித் தீர்த்தேன் — Stack / Queue Design பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
A queue gives first-in-first-out, a stack needs last-in-first-out. After pushing a new element, rotate the queue (pop from the front and push to the back) n−1 times so the new element ends up at the front — then pop and top are just the queue's front.
Approach
- 1
push: enqueue x, then move the other n−1 elements behind it.
- 2
pop: dequeue the front.
- 3
top: peek the front.
- 4
empty: queue is empty.
நான் எப்படித் தீர்த்தேன்
Single queue, rotate on pushPythonO(n) push
from collections import deque
class MyStack:
def __init__(self):
self.Q1 = deque()
self.Q2 = deque()
def push(self, x):
self.Q1.append(x)
for i in range(len(self.Q1) - 1):
self.Q1.append(self.Q1.popleft())
def pop(self):
if not self.Q1:
return None
return self.Q1.popleft()
def top(self):
if not self.Q1:
return None
return self.Q1[0]
def empty(self):
return len(self.Q1) == 0Implement Stack using Queues — அடிக்கடி கேட்கப்படும் கேள்விகள்
Implement Stack using Queues பின்னாலுள்ள intuition என்ன?
A queue gives first-in-first-out, a stack needs last-in-first-out. After pushing a new element, rotate the queue (pop from the front and push to the back) n−1 times so the new element ends up at the front — then pop and top are just the queue's front.
Implement Stack using Queues (LeetCode 225) ஐ எப்படித் தீர்ப்பது?
1. push: enqueue x, then move the other n−1 elements behind it. 2. pop: dequeue the front. 3. top: peek the front. 4. empty: queue is empty.
Implement Stack using Queues இன் time மற்றும் space complexity என்ன?
Time: O(n) push, O(1) pop/top. Space: O(n). (Accepted approach: Single queue, rotate on push.)
Implement Stack using Queues இல் பொதுவான தவறுகள் என்ன?
One queue is enough; the two-queue version is commented out in the code.