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

[LeetCode]Implement Queue using Stacks

2015-11-27 05:55 323 查看
俩stack模拟queue,每次往第一个里面push,要pop的时候pop第二个,如果第二个为空,先把第一个的都放到第二个里面,再pop第二个。平均下来每个数据的时间复杂度为o(1)

class MyQueue {
// Push element x to the back of queue.
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int x) {
stack1.push(x);
}

// Removes the element from in front of queue.
public void pop() {
if (!stack2.isEmpty()) {
stack2.pop();
} else {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
stack2.pop();
}
}

// Get the front element.
public int peek() {
if (!stack2.isEmpty()) {
return stack2.peek();
} else {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.peek();
}
}

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