題目:
面試題09. 用兩個棧實現隊列
題解:
232. 用棧實現隊列
代碼:
import java.util.*;
public class 面試題09 {
public static class CQueue {
Stack<Integer> s1;
Stack<Integer> s2;
public CQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void appendTail(int value) {
s1.push(value);
}
public int deleteHead() {
if (s1.empty() && s2.empty()) {
return -1;
}
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.pop();
}
}
public static void main(String[] args) {
CQueue obj = new CQueue();
int value = 5;
obj.appendTail(value);
int param_2 = obj.deleteHead();
System.out.println(param_2);
}
}
參考:
class CQueue {
LinkedList<Integer> stack1;
LinkedList<Integer> stack2;
public CQueue() {
stack1 = new LinkedList<>();
stack2 = new LinkedList<>();
}
public void appendTail(int value) {
stack1.add(value);
}
public int deleteHead() {
if (stack2.isEmpty()) {
if (stack1.isEmpty()) return -1;
while (!stack1.isEmpty()) {
stack2.add(stack1.pop());
}
return stack2.pop();
} else return stack2.pop();
}
}