《剑指offer》—— 9 用两个栈实现队列

题目

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值