代码随想录第十天|栈实现队列、队列实现栈

Leetcode 232. 用栈实现队列

题目链接: 用栈实现队列
自己的思路:使用两个栈来模拟队列,栈s_in来进行输入,栈s_out来进行输出;难点在于pop和peek处,当s_out为空的时候,将s_in中的元素都放到s_out中

正确思路:

代码:

class MyQueue {
Stack<Integer> s_in;
Stack<Integer> s_out;
    public MyQueue() {
        s_in = new Stack<>();
        s_out = new Stack<>();
    }
    
    public void push(int x) {
        s_in.push(x);
    }
    
    public int pop() {
        move();
        return s_out.pop();
    }
    
    public int peek() {
        move();
        return s_out.peek();
    }
    
    public boolean empty() {
        return s_in.isEmpty()&&s_out.isEmpty();
    }

    public void move(){
        if (!s_out.isEmpty()){
        }else{
            while(!s_in.isEmpty()){
                s_out.push(s_in.pop());
            }
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

Leetcode 225. 用队列实现栈

题目链接: 用队列实现栈
自己的思路:没想出来

正确思路:使用两个队列来实现栈的操作;实质是一个队列的操作,另一个队列是辅助队列,辅助队列用于反转目标队列的元素顺序:先将元素加入到辅助队列中,然后再将目标队列中的元素加入到辅助队列中,最后再交换两个队列即可。

代码:

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

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值