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

Implement Queue using Stacks

2015-07-09 14:37 453 查看
class MyQueue {
// Using two stacks.
Stack<Integer> s1 = new Stack<Integer>();// Pop out.
Stack<Integer> s2 = new Stack<Integer>();// Cache.

// Push element x to the back of queue.
public void push(int x) {
s2.push(x);
}

// Removes the element from in front of queue.
public void pop() {
if (empty()) {
return;
}
if (s1.isEmpty()) {
while (!s2.isEmpty()) {
s1.push(s2.peek());
s2.pop();
}
}
s1.pop();
}

// Get the front element.
public int peek() {
if (empty()) {
return -1;
}
if (s1.isEmpty()) {
while (!s2.isEmpty()) {
s1.push(s2.peek());
s2.pop();
}
}
return s1.peek();
}

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