Title Description:
Implement the following operations of a queue using stacks.
- Push (x)--push element x to the back of the queue.
- Pop ()--Removes the element from in front of the queue.
- Peek ()--Get the front element.
- Empty ()--Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack--which means only
push to top
, peek/pop from top
, size
, and is empty
operations AR E valid.
- Depending on your language, stack may is not supported natively. You could simulate a stack by using a list or deque (double-ended queue), as long as if you have standard operations of a s Tack.
- You may assume this all operations is valid (for example, no pop or peek operations would be called on an empty queue).
Problem Solving Ideas:
Using two stacks, one for inserting data and the other for outputting data.
The code is as follows:
Class Myqueue { stack<integer> input = new stack<integer> (); stack<integer> output = new stack<integer> (); Push element x to the back of the queue. public void push (int x) { input.push (x); } Removes the element from in front of the queue. public void Pop () { peek (); Output.pop (); } Get the front element. public int Peek () { if (Output.empty ()) {" while (!input.empty ()) { Output.push (Input.pop ()) } }} return Output.peek (); } Return whether the queue is empty. public Boolean empty () { return input.empty () && output.empty ();} }
Java [Leetcode 232]implement Queue using Stacks