【知识积累】如何用栈结构实现队列结构

package com.example.demo.algorithm.D002;

import java.util.Stack;

/**
 * @Description :
 * 如何用栈结构实现队列结构
 *
 * 准备两个栈
 * 一个push栈 一个pop栈
 * push栈向pop栈倒入数据
 * 1、每次pop栈为空时,才能倒入数据
 * 2、一次性要把push栈的数据倒完
 *
 * 当添加一个数据时,将数据添加到push栈,然后将push栈的数据全部倒入pop栈
 * 当弹出一个数据时,将push栈的数据全部倒入pop栈,然后弹出pop栈的栈顶
 *
 * @Author : Darren
 * @Date : 2021 年 02 月 18 日 21:17:16
 * @since : 1.0
 */
public class J006_TwoStackImplementQueue {

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

    public static class TwoStackQueue{

        private Stack<Integer> stackPush;
        private Stack<Integer> stackPop;

        public TwoStackQueue() {
            this.stackPush = new Stack<>();
            this.stackPop = new Stack<>();
        }

        /**
         * push栈向pop栈倒入数据
         * 1、每次pop栈为空时,才能倒入数据
         * 2、一次性要把push栈的数据倒完
         */
        public void pushToPop(){
            if (this.stackPop.isEmpty()){
                while (!this.stackPush.isEmpty()){
                    this.stackPop.push(stackPush.pop());
                }
            }
        }

        public void add(Integer value){
            this.stackPush.push(value);
            this.pushToPop();
        }

        public Integer poll(){
            if (this.stackPush.isEmpty() && this.stackPop.isEmpty()){
                throw new RuntimeException("queue is empty");
            }
            this.pushToPop();
            return this.stackPop.pop();
        }

        public Integer peek(){
            if (this.stackPush.isEmpty() && this.stackPop.isEmpty()){
                throw new RuntimeException("queue is empty");
            }
            this.pushToPop();
            return this.stackPop.peek();
        }
    }
}

 

Guess you like

Origin blog.csdn.net/axin1240101543/article/details/113846255