剑指offer9用两个栈实现队列

33 阅读1分钟

没什么好说的这个题,基本上熟悉数据结构都能复现出来。

class CQueue { LinkedList stack1; LinkedList 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();
}

}