This content originally appeared on DEV Community and was authored by Se-ok Jeon
Constraints
- 1 <= x <= 9
- At most 100 calls will be made to push, pop, peek, and empty.
- All the calls to pop and peek are valid.
Idea #1 (Time: ?, Memory: ?)
- push: stack push
- pop: iterate until next node of stack is None and return node.data with prev.next = None
- peek: same as pop but not
prev.next = None
- empty: stack.isempty()
Test Cases
Example 1:
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: 1, 2
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
Code
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
if self.top is None:
self.top = Node(data)
else:
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
if self.top is None:
return None
node = self.top
self.top = self.top.next
return node.data
def peek(self):
if self.top is None:
return None
return self.top.data
def is_empty(self):
return self.top is None
class MyQueue:
def __init__(self):
self.mystack = Stack()
def push(self, x: int) -> None:
self.mystack.push(x)
def pop(self) -> int:
if self.mystack.top.next is None: return self.mystack.pop()
node = self.mystack.top
prev = None
while node.next:
prev = node
node = node.next
res = node.data
prev.next = None
return res
def peek(self) -> int:
node = self.mystack.top
prev = None
while node:
prev = node
node = node.next
return prev.data
def empty(self) -> bool:
return self.mystack.is_empty()
This content originally appeared on DEV Community and was authored by Se-ok Jeon
Se-ok Jeon | Sciencx (2024-10-06T11:48:47+00:00) 232. Implement Queue using Stacks. Retrieved from https://www.scien.cx/2024/10/06/232-implement-queue-using-stacks/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.