題目
兩個棧實現(xiàn)隊列
題解
比較簡單 就不多解釋了 看代碼吧
class Queue {
private Deque<Integer> stackIn = new LinkedList<>();
private Deque<Integer> stackOut = new LinkedList<>();
private int defaultValue = -1;
public void offer(int value) {
stackIn.push(value);
}
public int poll() {
if (stackOut.isEmpty()) {
if (stackIn.isEmpty()) {
return defaultValue;
} else {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
return stackOut.pop();
}
}
題目
兩個隊列實現(xiàn)棧
題解
也不難 不浪費時間了
class Stack {
private Deque<Integer>[] queues = new Deque[]{new LinkedList<Integer>(), new LinkedList<Integer>()};
private int status = 0;
private int defaultValue = -1;
public void push(int value) {
queues[status % 2].offer(value);
}
public int pop() {
while (true) {
int index = status % 2;
int next = (status + 1) % 2;
if (queues[index].size() < 1) return defaultValue;
while (queues[index].size() > 1)
queues[next].offer(queues[index].poll());
status=(status+1)%2;
return queues[index].poll();
}
}
}
總結: 這類題目考驗對數(shù)據(jù)結構的理解皂甘,與靈活性斧散,不要死記硬背供常,練死勁,講究四兩撥千斤鸡捐,接化發(fā)栈暇,更不能搞偷襲,耍小聰明來湊夠字數(shù) 哈
源碼: 劍指offer4J