package com.zmz.algorithm.stackQueue;

import java.util.Stack;

/**
 * @author 张明泽
 * Create by 2022/5/31 17:56
 * 用栈实现队列
 * LeetCode-232
 */
public class StackImplQueue {
    private Stack<Integer> stackInput;
    private Stack<Integer> stackOutput;
    public static void main(String[] args) {
        Stack stack = new Stack();
        StackImplQueue stackImplQueue = new StackImplQueue();
        stackImplQueue.push(1);
        stackImplQueue.push(2);
        stackImplQueue.push(3);
        int num1 = stackImplQueue.pop();
        int num2 = stackImplQueue.peek();
        Boolean f = stackImplQueue.empty();
        System.out.println("弹出的" + num1);
        System.out.println("第一个元素" + num2);
        System.out.println("是否为空" + f);
    }
    public StackImplQueue() {
        stackInput = new Stack<>();
        stackOutput = new Stack<>();
    }

    public void push(int x) {
        stackInput.push(x);
    }

    public int pop() {
        if (stackOutput.isEmpty()) {
            while (!stackInput.isEmpty()) {
                stackOutput.push(stackInput.pop());
            }
        }
        return stackOutput.pop();
    }

    public int peek() {
        if (stackOutput.isEmpty()) {
            while (!stackInput.isEmpty()) {
                stackOutput.push(stackInput.pop());
            }
        }
        return stackOutput.peek();
    }

    public boolean empty() {
        return stackOutput.isEmpty() && stackInput.isEmpty();
    }
}
最后修改:2022 年 06 月 02 日 10 : 20 AM
赏杯咖啡喝 谢谢您~