Implement Queue using Stack

Stack / Queues Implementation Easy

Implement a First-In-First-Out (FIFO) queue using a single stack. The implemented queue should support the following operations: push, pop, peek, and isEmpty.


Implement the StackQueue class:


void push(int x): Adds element x to the end of the queue.

int pop(): Removes and returns the front element of the queue.

int peek(): Returns the front element of the queue without removing it.

boolean isEmpty(): Returns true if the queue is empty, false otherwise.

Examples:

Input:

["StackQueue", "push", "push", "pop", "peek", "isEmpty"]

[[], [4], [8], [], [], []]

Output:[null, null, null, 4, 8, false]

Explanation:

StackQueue queue = new StackQueue();

queue.push(4);

queue.push(8);

queue.pop(); // returns 4

queue.peek(); // returns 8

queue.isEmpty(); // returns false

Input:

["StackQueue", "isEmpty"]

[[]]

Output: [null, true]

Explanation:

StackQueue queue = new StackQueue();

queue.isEmpty(); // returns true

Input:

["StackQueue", "push", "pop", "isEmpty"]

[[], [6], [], []]

Constraints

  • 1 <= numbers of calls made <= 100
  • 1 <= x <= 100

Hints

  • To implement a queue using a single stack, we need to reverse the order when dequeuing elements.
  • "Calling pop() or peek() on an empty queue should raise an appropriate exception. Ensure isEmpty() accurately reflects whether the queue has elements."

Company Tags

GE Healthcare Deloitte eBay Zoho Red Hat Mastercard DoorDash Roblox PayPal Oracle KPMG Dropbox Alibaba HCL Technologies Airbnb Texas Instruments Zomato Chewy IBM Twilio Bain & Company Siemens Healthineers Bungie Roche Splunk Google Microsoft Amazon Meta Apple Netflix Adobe TCS Cognizant Accenture Infosys Capgemini Wipro