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 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).
Title Description://Use the stack to implement the following operations of the queue://push (x)--add element x to the tail of the queue//pop ()--Remove the element from the head of the queue//peek ()--Get the team head element//empty ()--Returns whether the queue is empty// Note: You can only use the standard operation of the stack, which means that only the push to top (stack), the Peek/pop from top (take the top of the stack/top of the stack),//And empty (judgment is empty) is allowed, depending on your language, the stack may not be built-in support. You can use list (list) or deque (double-ended queue) to simulate,//to ensure that only the standard operation of the stack, you can assume that all operations are valid (for example, do not perform a pop or peek operation on an empty queue)//solution: With two stacks to simulate a queue, The basic idea is two LIFO = FIFO,//element into the queue always into the in stack, the element out of the queue if the out stack is not empty directly eject the out stack header element;//If the out stack is empty, the in stack element out of the stack all pressed into the out stack, and then popped out of the stack, so that the simulation of a The core is to ensure that each element out of the stack has been in,out two stacks, so that the implementation of two LIFO = FIFO first. Class Queue {public:stack<int> in;stack<int> out;void Move () {//move all elements inside the in stack to the out stack while (!in.empty ()) {int X = In.top (); In.pop (); Out.push (x);}} Push element x to the back of queue.void push (int x) {in.push (x);} Removes the element from in front of queue.void pop (void) {if (Out.empty ()) {move ()}; if (!out.empty ()) {Out.pop ();}} Get the front element.int peek (void) {if (Out.empty ()) {move ();} if (!out.empty ()) {return out.top ();}} Return whether the queue is empty.bool empty (void) {return in.empty () && out.empty ();}};
Leetcode 232:implement Queue using Stacks