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 the only standard operations of a queue – which means only
push to back
,, peek/pop from front
size
, and is empty
operations AR E 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).
classStack {Private: Queue<int> que[2]; intCurrent ; voidTransfer (queue<int>& que1, queue<int>& Que2,intN) { for(intI=0; i<n; i++) {Que2.push (Que1.front ()); Que1.pop (); } } Public: Stack (): Current (0){} //Push element x onto stack. voidPushintx) {que[current].push (x); } //removes the element on top of the stack. voidpop () {intNums =que[current].size (); if(Nums = =0) { return; } transfer (Que[current], que[1-current], nums-1); Que[current].pop (); Current=1-Current ; } //Get the top element. intTop () {if(Empty ()) {return 0; } returnQue[current].back (); } //Return Whether the stack is empty. BOOLempty () {returnQue[current].empty (); }};
You can also use a queue to complete, but for the queue one and two are no different than just a pointer.
Leetcode Implement Stack using Queues