DEV Community

Se-ok Jeon
Se-ok Jeon

Posted on

232. Implement Queue using Stacks

Constraints

  1. 1 <= x <= 9
  2. At most 100 calls will be made to push, pop, peek, and empty.
  3. All the calls to pop and peek are valid.

Idea #1 (Time: ?, Memory: ?)

  1. push: stack push
  2. pop: iterate until next node of stack is None and return node.data with prev.next = None
  3. peek: same as pop but not prev.next = None
  4. 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() 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)