225. Implement Stack using Queues
class MyStack {
//pop: pooll & offer elelments to the tail of the euque,
// EXCEPT the last one
// then pop the queue
Queue<Integer> queue = new LinkedList<>();
int topNum;
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
queue.offer(x);
topNum=x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int i=0;
while(i++<queue.size()-1){
if(i == queue.size()-1) topNum=queue.peek();
queue.offer(queue.poll());
}
return queue.poll();
}
/** Get the top element. */
public int top() {
return topNum;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
/**
* Your MyStack object will 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();
*/
Last updated
Was this helpful?