剑指offer(8) 用两个栈实现队列

题目

  用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。

 

思路

  这道题较简单,自己先试着模拟一下插入删除的过程(在草稿纸上动手画一下):插入肯定是往一个栈stack1中一直插入;删除时,直接出栈无法实现队列的先进先出规则,这时需要将元素从stack1出栈,压到另一个栈stack2中,然后再从stack2中出栈就OK了。需要稍微注意的是:当stack2中还有元素,stack1中的元素不能压进来;当stack2中没元素时,stack1中的所有元素都必须压入stack2中。否则顺序就会被打乱。

测试用例

  1.往空队列添加删除元素

  2.往非空队列添加删除元素

  3.删除至队列为空

 

完整Java代码

public class QueueWithTwoStacks {
     
    class Queue{
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
         
        /**
         * 插入结点
         */
        public void push(int node) {
            stack1.push(node);
        }
         
        /**
         * 删除结点
         */
        public int pop() {
            if (stack2.empty()) {
                if (stack1.empty())
                    throw new RuntimeException("队列为空!");
                else {
                    while (!stack1.empty())
                        stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }
     
     
    //=======测试代码==========
     
    public void test1() {
        Queue queue= new Queue();
        queue.push(1);
        queue.push(2);
        System.out.println(queue.pop());
        queue.push(3);
        System.out.println(queue.pop());
        System.out.println(queue.pop());
    }
     
    /**
     * 往空队列删除元素
     */
    public void test2() {
        Queue queue= new Queue();
        System.out.println(queue.pop());
    }
     
    public static void main(String[] args) {
        QueueWithTwoStacks demo = new QueueWithTwoStacks();
        demo.test1();      
        demo.test2();
    }
 
}

 

1
2
3
Exception in thread "main" java.lang.RuntimeException: 队列为空!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值