Leetcodement: Implement Queue using Stacks, bluestacks
Implement the following operations of a queue using stacks.
- Push (x)-Push element x to the back of queue.
- Pop ()-Removes the element from in front of 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 are
Valid.
- Depending on your language, stack may not be supported natively. You
May simulate a stack by using a list or deque (double-ended queue ),
As long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or
Peek operations will be called on an empty queue ).
Stack is used to implement a queue. This topic has been mentioned in "Sword finger offer" before, and there is nothing to say. Two stacks are used. One stack is used to save the inserted elements, and the other stack is used to perform pop or top operations. When performing pop or top operations, check whether the other stack is empty, if it is empty, all the elements in the first stack will pop up and be inserted to the Second stack. Then, the elements in the Second stack will pop up. Note that there is a skill in programming this question. You can use peek to implement pop, which can reduce repeated code. You need to be able to extend your thinking during programming. If the pop function declaration is stuck in the process of using pop to implement the peek function, you will feel like you have no way to start.
Runtime: 0 ms
Class Queue {public: // Push element x to the back of queue. void push (int x) {pushStack. push (x);} // Removes the element from in front of queue. void pop (void) {peek (); // here, you can use peek to transfer elements between two stacks to avoid repeated code popStack. pop ();} // Get the front element. int peek (void) {if (popStack. empty () {while (! PushStack. empty () {popStack. push (pushStack. top (); pushStack. pop () ;}return popStack. top ();} // Return whether the queue is empty. bool empty (void) {return pushStack. empty () & popStack. empty ();} private: stack <int> pushStack; // The data is inserted into the stack. <int> popStack; // The data is popped up from the stack };
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.