Leetcode Problem 225. Implement Stack using Queues

225. Implement Stack using Queues

Leetcode Solutions

Approach # (Two Queues, push - O(), pop O(n))

  1. Initialize two empty queues, q1 and q2, and a variable topElement to store the top of the stack.
  2. For push, enqueue the new element to q1 and update topElement.
  3. For pop, transfer all elements except the last from q1 to q2, save the last element to return, and swap the references of q1 and q2.
  4. For top, return topElement.
  5. For empty, check if q1 is empty and return the result.
UML Thumbnail

Approach # (One Queue, push - O(n), pop O())

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...