如何用栈实现队列?

问题出自程序员小灰 - 如何用栈实现队列?

代码实现


import java.util.*;

public class DummyQueue {

    Stack<Integer> stack1;

    Stack<Integer> stack2;

    DummyQueue(){

        stack1 = new Stack<Integer>();

        stack2 = new Stack<Integer>();

    }

    public void offer(int num) {

        stack1.push(num);

    }

    public int peek() {

        if(!stack2.isEmpty()) {

            return stack2.peek();

        }

        dropStack();

        return stack2.peek();

    }

    public int pull() {

    if(!stack2.isEmpty()) {

        return stack2.pop();

    }    

    dropStack();

        return stack2.pop();

    }

    public void dropStack() {

        while(!stack1.isEmpty()) {

            stack2.push(stack1.pop());

        }

        return;

    }

    public static void main(String[] args) {

        DummyQueue queue = new DummyQueue();

        queue.offer(1);

        queue.offer(2);

        queue.offer(3);

        System.out.println(queue.peek());

        System.out.println(queue.pull());

        System.out.println(queue.pull());

        queue.offer(4);

        queue.offer(5);

        System.out.println(queue.pull());

        System.out.println(queue.pull());

        System.out.println(queue.pull());

        System.out.println(queue.pull());

    }

}

测试结果

image
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,861评论 25 708
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,838评论 2 59
  • 慈航_3596阅读 322评论 0 0
  • 特别喜欢这个颜色,美丽的花花。 但是画的还有问题,以后还得再画一遍。 临摹那仁的画
    鲜影儿阅读 378评论 6 6
  • 不知不觉,离考研只有70多天了。昨晚和老富通了语音,期间一直没有控制住自己烦躁的心情。在过去的200天里,...
    Jojo_Zhan阅读 557评论 0 1