美文网首页
两个栈实现队列

两个栈实现队列

作者: 事件_666 | 来源:发表于2019-05-29 13:32 被阅读0次

import java.util.Stack;

public class Problem_02_TwoStacksImplementQueue {

public static class TwoStacksQueue {
    public Stack<Integer> stackPush;
    public Stack<Integer> stackPop;

    public TwoStacksQueue() {
        stackPush = new Stack<Integer>();
        stackPop = new Stack<Integer>();
    }

    // 核心函数  push栈向pop栈倒入数据  
    private void pushToPop() {
        if (stackPop.empty()) {
            while (!stackPush.empty()) {
                stackPop.push(stackPush.pop());
            }
        }
    }

    public void add(int pushInt) {
        stackPush.push(pushInt);
        pushToPop();
    }

    public int poll() {
        if (stackPop.empty() && stackPush.empty()) {
            throw new RuntimeException("Queue is empty!");
        }
        pushToPop();
        return stackPop.pop();
    }

    public int peek() {
        if (stackPop.empty() && stackPush.empty()) {
            throw new RuntimeException("Queue is empty!");
        }
        pushToPop();
        return stackPop.peek();
    }
}

public static void main(String[] args) {
    TwoStacksQueue test = new TwoStacksQueue();
    test.add(1);
    test.add(2);
    test.add(3);
    System.out.println(test.peek());
    System.out.println(test.poll());
    System.out.println(test.peek());
    System.out.println(test.poll());
    System.out.println(test.peek());
    System.out.println(test.poll());
}

}

相关文章

  • 栈和队列

    两个栈实现队列 两个队列实现栈

  • 栈&队列

    一、栈&队列总结 栈/队列的应用接雨水验证栈序列滑动窗口的最大值 栈/队列的特殊实现用两个栈实现队列用两个队列实现...

  • 队列、栈

    两个队列实现一个栈 两个栈实现一个队列

  • 面试题9: 用两个栈实现队列

    9-1 用两个栈实现队列 9-2 用两个队列实现栈

  • 手撕栈队列

    【面试题07:用两个栈实现队列】 题目:利用两个栈实现队列的插入,取队首,判断非空等函数。拓展:用两个队列实现栈,...

  • 用两个栈实现队列,用两个队列实现堆栈

    参考:剑指Offer面试题7(Java版):用两个栈实现队列与用两个队列实现栈 用两个栈实现队列stack1作为入...

  • 栈和队列的相互实现

    两个栈实现队列: 一个栈用来入,一个栈用来出 两个队列实现栈: 入栈的时候正常存入一个队列,出栈的时候用另一个队列...

  • Swift-两个栈实现队列

    题目:两个栈实现队列,栈是先入后出,队列是先入先出,两个栈可以利用这个特点实现队列. 核心代码: `class ...

  • LeetCode 每日一题 [43] 用两个栈实现队列

    LeetCode 用两个栈实现队列 [简单] 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appen...

  • 剑指Offer

    09 用两个栈实现队列 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 del...

网友评论

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

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