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

leetcode-java-225. Implement Stack using Queues

2016-06-15 22:04 447 查看
class MyStack {
// Push element x onto stack.
List<Integer> queue1 = new LinkedList<Integer>();
List<Integer> queue2 = new LinkedList<Integer>();

public void push(int x) {
if(!queue1.isEmpty()) {
queue1.add(x);
} else {
queue2.add(x);
}
}

// Removes the element on top of the stack.
public void pop() {
// 两个队列中至少有一个为空,将queue1设置非空
if(queue1.isEmpty()) {
List<Integer> tmp = queue2;
queue2 = queue1;
queue1 = tmp;
}

while(queue1.size() > 1) {
queue2.add(queue1.remove(0));
}

queue1.clear();
}

// Get the top element.
public int top() {
// 两个队列中至少有一个为空,将queue1设置非空
if(queue1.isEmpty()) {
List<Integer> tmp = queue2;
queue2 = queue1;
queue1 = tmp;
}

while(queue1.size() > 1) {
queue2.add(queue1.remove(0));
}
queue2.add(queue1.get(0));

return queue1.remove(0);
}

// Return whether the stack is empty.
public boolean empty() {
return queue1.isEmpty() && queue2.isEmpty();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: