Topic:
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).
Test instructions: Using queue to simulate stack, using the basic operation of queue
Idea: Relatively simple, with two queue to carry out, a stack as a simulation storage, a transport to convert the middle of the operation of the number
Code:
classMystack {LinkedList<Integer> queue =NewLinkedlist<integer>(); LinkedList<Integer> temp =NewLinkedlist<integer>(); //Push element x onto stack. Public voidPushintx) { while(!Queue.isempty ()) {Temp.offer (Queue.poll ()); } queue.offer (x); while(!Temp.isempty ()) {Queue.offer (Temp.poll ()); } } //removes the element on top of the stack. Public voidpop () {queue.poll (); } //Get the top element. Public intTop () {returnQueue.peek (); } //Return Whether the stack is empty. Public Booleanempty () {returnQueue.isempty (); }}
[Leetcode-java] Implement Stack using Queues