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).
Update (2015-06-11):
The class name of the Java function had been updated to Mystack instead of Stack.
Problem Solving Ideas:
Implemented with the instance LinkedList of the queue, the Java implementation is as follows:
Class Mystack {linkedlist<integer> queue; Mystack () {this.queue = new linkedlist<integer> ();} Push element x onto stack.public void push (int x) {queue.add (x);} Removes the element on top of the Stack.public void Pop () {queue.remove (Queue.size ()-1);} Get the top element.public int top () {return queue.getlast ();} Return whether the stack is empty.public boolean empty () {return queue.isempty ();}}
Java for Leetcode 225 Implement Stack using Queues