0
点赞
收藏
分享

微信扫一扫

用栈实现队列-232-[简单]

MaxWen 2022-03-25 阅读 45
leetcode

 主要思路

  • 用两个栈
  • 一个插入栈,一个弹出栈
  • 当弹出栈为空的时候,将插入栈的数据迁移到弹出栈
  • 这样两个栈倒腾就能实现队列的先进先出

 

package com.company.myQueue;

import java.util.Stack;

public class MyQueue {

    Stack<Integer> insertStack = new Stack<>();

    Stack<Integer> popStack = new Stack<>();

    public MyQueue() {
    }

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

    public int pop() {
        if (popStack.isEmpty()) {
            while (!insertStack.isEmpty()) {
                popStack.push(insertStack.pop());
            }
        }

        //假设一个空的队列不会调用 pop(),否者这儿要判空
        return popStack.pop();
    }

    public int peek() {
        if (popStack.isEmpty()) {
            while (!insertStack.isEmpty()) {
                popStack.push(insertStack.pop());
            }
        }

        //假设一个空的队列不会调用 peek(),否者这儿要判空
        return popStack.peek();

    }

    public boolean empty() {
        if (insertStack.isEmpty() && popStack.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}
举报

相关推荐

0 条评论