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 may assume this all operations is valid (for example, no pop or top operations would be called on an empty stack).
- 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-which means only
push to back
,, pop from front
, size
and is empty
operations is valid.
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and all test cases.
Water problem.
1 classStack {2 Private:3queue<int> que[2];4 intCur =0;5 6 Public:7 //Push element x onto stack.8 voidPushintx) {9 Que[cur].push (x);Ten } One A //removes the element on top of the stack. - voidPopvoid) { - while(Que[cur].size () >1) { theque[1-Cur].push (Que[cur].front ()); - Que[cur].pop (); - } - Que[cur].pop (); +Cur =1-cur; - } + A //Get the top element. at intTopvoid) { - while(Que[cur].size () >1) { -que[1-Cur].push (Que[cur].front ()); - Que[cur].pop (); - } - inttop =Que[cur].front (); inque[1-Cur].push (Que[cur].front ()); - Que[cur].pop (); toCur =1-cur; + returntop; - } the * //Return Whether the stack is empty. $ BOOLEmptyvoid) {Panax Notoginseng returnque[cur].empty (); - } the};
[Leetcode] Implement Stack using Queues