leetcode日记09

day09


栈与队列基础知识

栈:先进后出
队列:先进先出

例题 leetcode 232.用栈实现队列

链接:https://leetcode.cn/problems/implement-queue-using-stacks/

思路:用两个栈模拟队列的先进先出的模式。一个用来输入,一个用来输出。pop操作时本题的重点,若输出栈为空,
则将输入栈的内容全部导入,若输出栈不为空,直接获取输出栈内的数据即可。

class MyQueue {
    Stack <Integer> stackIn;
    Stack <Integer> stackOut;
    int size;
    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
        size = 0;
    }
    
    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();
    }

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

例题 leetcode 225.用队列实现栈

链接:https://leetcode.cn/problems/implement-stack-using-queues/

思路:用两个队列来实现,一个是弹出顺序和栈一致的队列,另外一个在push的时候保持元素顺序。
和用栈实现队列不太一样。

class MyStack {
    Queue<Integer> que1;
    Queue<Integer> que2;
    int size;
    public MyStack() {
        que1 = new LinkedList<>();
        que2 = new LinkedList<>();
        size = 0;
    }
    
    public void push(int x) {
        que2.offer(x);
        while(! que1.isEmpty()){
            que2.offer(que1.poll());
        }
        Queue<Integer> temp = que1;
        que1 = que2;
        que2 = temp;
    }
    
    public int pop() {
        return que1.poll();
    }
    
    public int top() {
        return que1.peek();
    }
    
    public boolean empty() {
        return que1.isEmpty();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值