题目
两个栈实现队列
题解
比较简单 就不多解释了 看代码吧
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();
}
}
题目
两个队列实现栈
题解
也不难 不浪费时间了
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();
}
}
}
总结: 这类题目考验对数据结构的理解,与灵活性,不要死记硬背,练死劲,讲究四两拨千斤,接化发,更不能搞偷袭,耍小聪明来凑够字数 哈
源码: 剑指offer4J