题目
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deletedHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。
思路
- 队列是先进先出的结构,栈是先进后出的结构。添加元素时放入Stack1。删除时要删除的元素在栈底,所以全部弹出到Stack2,此时要删除的元素在Stack2的栈顶,可以删除。
- 再添加新的元素时依然放入Stack1。
- 即:如果Stack2不空,那么栈顶的元素一定是最先入Stack1中的元素(Stack2不空时不能将Stack1中元素弹出到Stack2);Stack2为空时,最先进入Stack1的元素在Stack1栈底,将Stack1弹出到Stack2,Stack2栈顶是最先进栈的元素。
代码
public class Queue{
private Stack<Integer> stack1 = new Stack<Integer>();
private Stack<Integer> stack2 = new Stack<Integer>();
public appendTail(int node){
stack1.push(node);
}
public deleteHead() throws Exception{
//如果stack2空,则将stack1弹入
if(stack2.isEmpty()){
while(!stack1.isEmpty){
stack2.push(stack1.pop());
}
}
//弹入后依然为空,说明队列空
if(stack2.isEmpty()){
throw new Exception("队列为空");
}
return stack2.pop();
}
}
题目
用两个队列实现一个栈。
思路
- 先往队列中插入的元素会先出来,但要符合栈的先进后出,则要让队列尾的元素弹出。可以把队列中除了队尾的元素全部保存到另一个队列,然后输出队尾。
代码
public class Stack {
Queue<Integer> queue1 = new ArrayBlockingQueue<Integer>();
Queue<Integer> queue2 = new ArrayBlockingQueue<Integer>();
public void appendTail(Integer data) {
queue1.add(data);
}
public Integer deleteTail() {
if(queue1.isEmpty() && queue2.isEmpty()) {
return null;
}
if(queue1.size() == 1) {
return queue1.poll();
}else if(queue1.size() > 0) {
while(queue1.size() > 1) {
queue2.add(queue1.poll());
}
return queue1.poll();
}else if(queue2.size() > 0) {
while(queue2.size() > 1) {
queue1.add(queue2.poll());
}
return queue2.poll();
}
return null;
}
}