美文网首页Java 杂谈Java
用两个栈实现队列

用两个栈实现队列

作者: firststep | 来源:发表于2019-04-16 17:15 被阅读0次

    题目:

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

    思路:

    1. 用两个栈来实现队列的操作,首先理解队列的属性是“先进先出”,栈是先进后出。
    2. 第一个栈来装属性,第二栈来输出属性。
    3. 当第二个栈为空的时候,把第一个栈的存到第二个栈里面输出,刚好符合队列的先进先出原则。
    4. 当第二个栈不为空的时候,直接pop出去。pop出去的刚好是第一个栈前面的内容同时符合先进先出原则。

    代码:

    package queueStudy;
    
    import java.util.Stack;
    
    public class QueueForStack {
        Stack<Integer> stackAdd = new Stack();
        Stack<Integer> stackOut = new Stack();
    
        public int pop() {
            if (stackOut.isEmpty()) {
                while(!stackAdd.isEmpty()){
                    stackOut.push(stackAdd.pop());
                }
            }
                return stackOut.pop();
        }
    
        public void push(int item) {
            stackAdd.push(item);
        }
    
        public static void main(String args[]) {
            QueueForStack queueForStack = new QueueForStack();
            queueForStack.push(1);
            queueForStack.push(2);
            queueForStack.push(3);
            System.out.print(queueForStack.pop());
            System.out.print(queueForStack.pop());
            System.out.print(queueForStack.pop());
            queueForStack.push(4);
            System.out.print(queueForStack.pop());
        }
    }
    
    

    运行结果:

    image.png

    感悟:

    少许的积累或许没有感觉,慢慢的沉淀才能蜕变成精华。

    相关文章

      网友评论

        本文标题:用两个栈实现队列

        本文链接:https://www.haomeiwen.com/subject/frtiwqtx.html