代码随想录算法训练营第10天| LeetCode 232.用栈实现队列 225. 用队列实现栈

232. 用栈实现队列

class MyQueue {

    private Stack<Integer> input;
    private Stack<Integer> output;


    public MyQueue() {
        input = new Stack<>();
        output = new Stack<>();
    }
    
    public void push(int x) {
        input.push(x);
    }
    
    public int pop() {
        if(output.isEmpty()){
            while(!input.isEmpty()){
                output.push(input.pop());
            }
        }
        return output.pop();
    }
    
    public int peek() {
        if(output.isEmpty()){
            while(!input.isEmpty()){
                output.push(input.pop());
            }
        }

        return output.peek();
    }
    
    public boolean empty() {

        return input.isEmpty()&& output.isEmpty();

    }
}

/**
 * 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();
 */

225. 用队列实现栈

class MyStack {
    
    private Queue<Integer> q1; // 主队列 用来存储栈的元素
    private 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、付费专栏及课程。

余额充值