您的位置:首页 > 产品设计 > UI/UE

Implement Stack using Queues

2015-09-18 13:37 337 查看
始终保证有一个队列是空的!

class MyStack {
// Push element x onto stack.
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();

public void push(int x) {
if (q1.isEmpty()) {
q2.add(x);
}
else{
q1.add(x);
}
}

// Removes the element on top of the stack.
public void pop() {
if (q2.isEmpty()) {
while (q1.size() != 1) {
q2.add(q1.poll());
}
q1.poll();
}
else{
while (q2.size() != 1) {
q1.add(q2.poll());
}
q2.poll();
}
}

// Get the top element.
public int top() {
int tmp;
if (q2.isEmpty()) {
while (q1.size() != 1) {
q2.add(q1.poll());
}
tmp = q1.peek();
q2.add(q1.poll());

}
else{
while (q2.size() != 1) {
q1.add(q2.poll());
}
tmp = q2.peek();
q1.add(q2.poll());

}
return tmp;
}

// Return whether the stack is empty.
public boolean empty() {

return q1.isEmpty() && q2.isEmpty();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: