Implement Stack using Queues
Total Accepted: 39756 Total Submissions: 130128 Difficulty: Easy
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.6px; 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.
Subscribe to see which companies asked this question
Hide TagsStack DesignHide Similar Problems(E) Implement Queue using Stacks
C + + code:
Class Stack {public://Push element x onto Stack. void push (int x) {q1.push (x); }//Removes the element on top of the stack. void Pop () {while (Q1.size () > 1) {int tmp = Q1.front (); Q1.pop (); Q2.push (TMP); } q1.pop (); while (!q2.empty ()) {int tmp = Q2.front (); Q2.pop (); Q1.push (TMP); }}/Get the top element. int Top () {while (Q1.size () > 1) {int tmp = Q1.front (); Q1.pop (); Q2.push (TMP); } int ret = Q1.front (); int t = Q1.front (); Q1.pop (); Q2.push (t); while (!q2.empty ()) {int tmp = Q2.front (); Q2.pop (); Q1.push (TMP); } return ret; }//Return whether the stack is empty. bool Empty () {return q1.empty () && q2.empty (); }private:queue<int> q1,q2;};
Leetcode:implement Stack using Queues