Question: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.
Example:
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
Answer
import java.util.LinkedList;
import java.util.Queue;
class MyStack {
private Queue<Integer> q = new LinkedList<>();
private Queue<Integer> temp = new LinkedList<>();
// add element x at queue top
void push(int x){
while(!q.isEmpty()){
temp.add(q.poll());
}
q.add(x);
while(!temp.isEmpty()){
q.add(temp.poll());
}
}
// remove
void pop(){
q.poll();
}
// retrieve but not remove
Integer top(){
return q.peek();
}
boolean empty(){
return q.isEmpty();
}
}
网友评论