Problem:
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.
Java Code:
class MyStack {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
int size = 0;
// Push element x onto stack.
public void push(int x) {
q1.add(x);
size++;
}
// Removes the element on top of the stack.
public void pop() {
if (size == 0) {
return;
}
int i = size;
while (i != 1) {
q2.add(q1.poll());
i--;
}
size--;
q1.poll();
Queue<Integer> tempQ = q1;
q1 = q2;
q2 = tempQ;
return;
}
// Get the top element.
public int top() {
if (size == 0) {
return 0;
}
int i = size;
while (i != 1) {
q2.add(q1.poll());
i--;
}
int tmp = q1.peek();
q2.add(q1.poll());
Queue<Integer> tempQ = q1;
q1 = q2;
q2 = tempQ;
return tmp;
}
// Return whether the stack is empty.
public boolean empty() {
return (q1.peek() == null) && (q2.peek() == null);
}
}
没有评论:
发表评论