Implement Stack using Queues
Implement the following operations of a stack using queues.
- Push (x)-push element x onto stack.
- Pop ()--Removes the element on top of the stack.
- Top ()--Get the top element.
- Empty ()--Return whether the stack is empty.
Notes:
- you must Use only standard operations of a queue--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 Back ,
peek/pop from front
, size
, And is empty
operations is valid.
- Depending on your language, queue May is not supported natively. You could simulate a queue by using a list or deque (double-ended queue), as long as if you have standard operations of a Q Ueue.
- You may assume this all operations is valid (for example, no pop or top operations would be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to Mystack instead of Stack.
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and all test cases.
Problem Solving Ideas:
Use two queues to simulate the stack. Records the current destination queue. Pressing the stack (push) pushes the element directly into the target queue. When the stack pops up (pop), the elements of the target queue are placed in another queue, leaving only one element. This element is then ejected. As with pop operations, the top operation places the elements of the target queue in another queue, leaving only one element, and then returning the element. The pop operation and top operations note the critical value of the target queue. If the destination queue is empty, the cache queue is used as the destination queue. The code is as follows:
Class Stack {public://Push element x onto Stack. void push (int x) {queuearr[currentqueue].push (x); }//Removes the element on top of the stack. void Pop () {if (Queuearr[currentqueue].empty ()) {Currentqueue = (currentqueue + 1)%2; } while (Queuearr[currentqueue].size ()!=1) {queuearr[(currentqueue + 1)%2].push (queuearr[currentqueue].fr ont ()); Queuearr[currentqueue].pop (); } queuearr[currentqueue].pop (); }//Get the top element. int Top () {if (Queuearr[currentqueue].empty ()) {Currentqueue = (currentqueue + 1)%2; } while (Queuearr[currentqueue].size ()!=1) {queuearr[(currentqueue + 1)%2].push (queuearr[currentqueue].fr ont ()); Queuearr[currentqueue].pop (); } return Queuearr[currentqueue].front (); }//Return whether the stack is empty. bool Empty () {return queuearr[0].empty () && queuearr[1].empty (); } Stack () {currentqueue = 0; } private:queue<int> queuearr[2]; int currentqueue;};
[Leetcode] Implement Stack using Queues