Topic:
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 < Code style= "Font-family:menlo,monaco,consolas, ' Courier New ', monospace; font-size:12.6000003814697px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">push to top ,
peek/pop from top
, size
, And is empty
operations is 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).
Solving:
Using the stack to implement the queue, this is more cumbersome than the queue to implement the stack, here to use two stacks, two ideas, the first is in the stack, the stack in reverse order on another stack, out of the time directly out of another stack on it. The second way of thinking, in the stack when not to do any processing, out of the stack when the stack in reverse order on another stack, out of another stack. Here are two kinds of code implementations.
Processing when the stack is in progress:
Class Myqueue { //Push element x to the back of the queue. Stack<integer> stack=new stack<> (); Stack<integer> stack2=new stack<> (); public void push (int x) { while (!stack.isempty ()) { Stack2.push (Stack.pop ()); } Stack2.push (x); while (!stack2.isempty ()) { Stack.push (Stack2.pop ()); } } Removes the element from in front of the queue. public void Pop () { stack.pop (); } Get the front element. public int Peek () { return Stack.peek (); } Return whether the queue is empty. public Boolean empty () { return stack.isempty (); }}
To process when the stack is out:
Class MyQueue2 { //Push element x to the back of the queue. Stack<integer> stack=new stack<> (); Stack<integer> stack2=new stack<> (); public void push (int x) { while (!stack2.isempty ()) Stack.push (Stack2.pop ()); Stack.push (x); } Removes the element from in front of the queue. public void POPs () { while (!stack.isempty ()) Stack2.push (Stack.pop ()); Stack2.pop (); } Get the front element. public int Peek () { while (!stack.isempty ()) Stack2.push (Stack.pop ()); return Stack2.peek (); } Return whether the queue is empty. public Boolean empty () { while (!stack2.isempty ()) Stack.push (Stack2.pop ()); return Stack.isempty (); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode232 Implement Queue using Stacks Java