Implement Stack using Queue

Stack / Queues Implementation Easy

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


Implement the QueueStack class:


void push(int x): Pushes element x onto the stack.

int pop(): Removes and returns the top element of the stack.

int top(): Returns the top element of the stack without removing it.

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

Examples:

Input:

["QueueStack", "push", "push", "pop", "top", "isEmpty"]

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

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

Explanation:

QueueStack stack = new QueueStack();

stack.push(4);

stack.push(8);

stack.pop(); // returns 8

stack.top(); // returns 4

stack.isEmpty(); // returns false

Input:

["QueueStack", "isEmpty"]

[[]]

Output:[null, true]

Explanation:

 QueueStack stack = new QueueStack();

stack.isEmpty(); // returns true

Input:

["QueueStack", "push", "pop", "isEmpty"]

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

Constraints

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

Hints

  • To implement a stack using a single queue, we need to reverse the order of elements within the queue after each push() operation.
  • After inserting a new element, rotate the queue so that the newest element moves to the front.

Company Tags

Bungie Goldman Sachs Alibaba Instacart Robinhood Zoho Siemens Healthineers Mastercard Activision Blizzard Pinterest HCL Technologies Freshworks Bloomberg Roche ARM Reddit MongoDB Flipkart Qualcomm Square Western Digital Electronic Arts Johnson & Johnson Lyft Cloudflare Google Microsoft Amazon Meta Apple Netflix Adobe TCS Cognizant Accenture Infosys Capgemini Wipro