栈和队列实战

实战:用两个栈来实现一个队列

整体思路

image

代码编写

package dataStructure.queue;

import org.omg.PortableInterceptor.INACTIVE;

import java.util.Stack;

public class TwoStackOneQueue {
    private Stack<Integer> stackPush;
    private Stack<Integer> stackPop;

    public TwoStackOneQueue(Stack<Integer> stackPush, Stack<Integer> stackPop) {
        this.stackPush = stackPush;
        this.stackPop = stackPop;
    }

    /**
     * 入队
     */
    public void add(int value){
        stackPush.push(value);
    }

    /**
     * 出队
     */
    public int pop(){
        if(stackPush.isEmpty() && stackPop.isEmpty()){
            throw new RuntimeException("队列不能为空");
        }

        if(stackPop.isEmpty()){
            while(!stackPush.isEmpty()){
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }

    public static void main(String[] args) {
        TwoStackOneQueue queue = new TwoStackOneQueue(new Stack<>(),new Stack<>());
        //入队
        queue.add(1);
        queue.add(2);

        System.out.println(queue.pop());//1
        System.out.println(queue.pop());//2
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容