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

225. Implement Stack using Queues

2016-06-09 21:43 309 查看
题目:https://leetcode.com/problems/implement-stack-using-queues/

代码:

class MyStack {
// Push element x onto stack.
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
public void push(int x) {
q1.add(x);
while(!q2.isEmpty()){
q1.add(q2.poll());
}
while(!q1.isEmpty()){
q2.add(q1.poll());
}
}
// Removes the element on top of the stack.
public void pop() {
q2.poll();
}
// Get the top element.
public int top() {
return q2.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}
111ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: