剑指Offer:面试题7——用两个栈实现队列(java实现)

题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

首先定义两个栈

Stack<Integer> stack1 = new Stack<Integer>();//作为进队的端口
Stack<Integer> stack2 = new Stack<Integer>();//作为出对的端口

思路:两个栈,有两个端口,那么肯定一个是用来入队的,另一个用来出队的。同时,由于栈是先进后出的,那么经过两次的入栈则会变为先进先出,即,第一次先进后出,第二次后进先出,两个加起来就变成了先进先出。

故,入队时,
为了保证队中的元素在当前元素之前,我们先从s2出栈,进入s1.

具体看代码:很简单

public void push(int node) {
        //检查是否满了?



        //将s2中的元素出栈,进栈到s1中
        while(!stack2.isEmpty()){
            int x = stack2.pop();
            stack1.push(x);
        }

        //node元素进栈
        stack1.push(node);

        //stack1中全体元素出栈,进入stack2中
        while(!stack1.isEmpty()){
            int x = stack1.pop();
            stack2.push(x);
        }
    }

  public int pop() {

    if(!stack2.isEmpty()){
        int x = stack2.pop();
        return x;
    }else{
        return -1;
    }
   }

当然这是从进队入手,出队简化。反之,我们也可以简化入队而让出队时考虑到应有情况。代码如下:

public void push(int node) {
        stack1.push(node);
    }

   public int pop() {

    //检查s2是否为空
    if(stack2.isEmpty()){
        //从stack1弹出元素并压入stack2
        while(!stack1.isEmpty()){
            int x = stack1.pop();
            stack2.push(x);
        }


    }

    //出队
    int head = stack2.pop();
    return head;
   }

相比之下,第二个方法更简单一些。

posted @ 2016-07-05 13:31  一只猫的爱园  阅读(196)  评论(0编辑  收藏  举报