【CT】LeetCode手撕—232. 用栈实现队列


题目


1- 思路

思路

  • ① 用两个栈来实现队列,一个 in 入栈 和一个 out 出栈
  • ② push 入队:入栈逻辑:即将元素加入到 in 栈 里即可
  • ③ pop 出队:出栈逻辑,先将 in栈 内容 依次弹出,加入到 out栈
  • ④ peek 取顶:先 pop 再 push,返回弹出的元素

2- 实现

⭐232. 用栈实现队列——题解思路

在这里插入图片描述

class MyQueue {


    Stack<Integer> stackIn;
    Stack<Integer> stackOut;

    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        dumpStackIn();
        return stackOut.pop();
    }
    
    public int peek() {
        dumpStackIn();
        return stackOut.peek();
    }
    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }


    public void dumpStackIn(){
        if(!stackOut.isEmpty()) return;
        while(!stackIn.isEmpty()){
            stackOut.push(stackIn.pop());
        }
    }
}

3- ACM 实现

public class MyQueue {

    Stack<Integer> stackIn ;
    Stack<Integer> stackOut ;

    public MyQueue(){
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }

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

    public int pop(){
        dumpIn();
        return stackOut.pop();
    }

    public int peek(){
        dumpIn();
        return stackOut.peek();
    }

    public boolean empty(){
        return stackIn.isEmpty()&&stackOut.isEmpty();
    }

    public void dumpIn(){
        if(!stackOut.isEmpty()) return;
        while(!stackIn.isEmpty()){
            stackOut.push(stackIn.pop());
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        MyQueue queue = new MyQueue();

        while (sc.hasNext()) {
            String command = sc.next();
            switch (command) {
                case "MyQueue":
                    queue = new MyQueue();
                case "push":
                    if (sc.hasNextInt()) {
                        int x = sc.nextInt();
                        queue.push(x);
                    }
                    break;
                case "pop":
                    System.out.println(queue.pop());
                    break;
                case "peek":
                    System.out.println(queue.peek());
                    break;
                case "empty":
                    System.out.println(queue.empty());
                    break;
            }
        }
        sc.close();
    }

}

  • 15
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值