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).
The stack consists of a queue, two approaches: 1, one queue implementation, Push is O (n), the other is O (1)
2, two queue implementations, pop is O (n), other things O (1)
classMystack {//One Queue solutionPrivatequeue<integer> q =NewLinkedlist<integer>();//Push element x onto stack. Public voidPushintx) {q.add (x); for(inti = 1; I < q.size (); i + +) {//rotate the queue to make the tail is the headQ.add (Q.poll ()); }}//removes the element on top of the stack. Public voidpop () {q.poll ();}//Get the top element. Public intTop () {returnQ.peek (); }//Return Whether the stack is empty. Public Booleanempty () {returnq.isempty ();}}
2.
Public classMystack {PrivateQueue<integer>queue1; PrivateQueue<integer>queue2; Private intnum; /**Initialize your data structure here.*/ PublicMystack () {queue1=NewLinkedList (); Queue2=NewLinkedList (); Num= 1; } /**Push element x onto stack.*/ Public voidPushintx) {if(num = = 1) {queue1.add (x); } Else{queue2.add (x); } } /**removes the element on top of the stack and returns that element.*/ Public intpop () {if(num = = 1){ intSize =queue1.size (); for(inti = 0; i < size-1; i++) {Queue2.add (Queue1.poll ()); } num= 2; returnQueue1.poll (); } Else { intSize =queue2.size (); for(inti = 0; i < size-1; i++) {Queue1.add (Queue2.poll ()); } num= 1; returnQueue2.poll (); } } /**Get the top element.*/ Public intTop () {if(num = = 1){ intSize =queue1.size (); for(inti = 0; i < size-1; i++) {Queue2.add (Queue1.poll ()); } inttop =Queue1.poll (); Queue2.add (top); Num= 2; returntop; } Else { intSize =queue2.size (); for(inti = 0; i < size-1; i++) {Queue1.add (Queue2.poll ()); } inttop =Queue2.poll (); Queue1.add (top); Num= 1; returntop; } } /**Returns Whether the stack is empty.*/ Public Booleanempty () {if(num = = 1){ returnQueue1.isempty (); } Else { returnQueue2.isempty (); } }}/*** Your Mystack object would be instantiated and called as such: * mystack obj = new Mystack (); * Obj.push (x); * int P Aram_2 = Obj.pop (); * int param_3 = Obj.top (); * Boolean param_4 = Obj.empty (); */
Leetcode 225. Implement stack using Queues using the queue build stack----------java