LintCode Implement Queue by Two Stacks

时间:2023-11-30 19:06:20

1. stack(先进后出):

pop 拿出并返回最后值; peek 返回最后值; push 加入新值在后面并返回此值。

2. queue(先进先出) :

poll = remove 拿出并返第一个值; element = peek 返第一个值; add = offer 加入新值在后面并返回true/false。

做此题时, 第一个stack为基础, 第二个stack为媒介来颠倒顺序, 加时从第一个加, 取时从第二个取。

public class Queue {
private Stack<Integer> stack1;
private Stack<Integer> stack2; public Queue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
// do initialization if necessary
} public void push(int element) {
stack1.push(element);
// write your code here
} public int pop() {
if(!stack2.empty()){
return stack2.pop();
} else{
while(stack1.size() > 0){
stack2.push(stack1.pop());
}
if(!stack2.empty()){
return stack2.pop();
} else return -1;
}
// write your code here
} public int top() {
if(!stack2.empty()){
return stack2.peek();
} else{
while(stack1.size() > 0){
stack2.push(stack1.pop());
}
if(!stack2.empty()){
return stack2.peek();
} else return -1;
}
// write your code here
}
}