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 and analysis: implement a stack with a standard queue. The key here is that when the add is complete, the point you just added will be in front of the queue, and the preceding points of the queue are taken out and added to the queue tail to implement this stack add function.
Code:
public class Mystack { queue<integer> Queue; /** Initialize your data structure here. * /Public mystack () { queue = new linkedlist<integer> (); } /** Push element x onto stack. */public void push (int x) { queue.add (x); for (int i=0;i<queue.size () -1;i++) { queue.add (Queue.poll ()); } } /** removes the element on top of the stack and returns that element. * /public int pop () { return queue.poll (); } /** Get the top element. * /public int top () { return Queue.peek (); } /** Returns Whether the stack is empty. * /public Boolean empty () { return queue.isempty (); }} /** * Your Mystack object would be instantiated and called as such: * mystack obj = new Mystack (); * Obj.push (x); * int param_2 = Obj.pop (); * int param_3 = Obj.top (); * Boolean param_4 = Obj.empty (); */
[Leetcode] 225. Implement Stack using Queues Java