leetcode232. 用栈实现队列(java)

这篇博客介绍了如何利用栈的数据结构实现队列的功能,包括push、pop、peek和empty操作。提供了两种不同的Java解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

使用栈实现队列的下列操作:

  • push(x) – 将一个元素放入队列的尾部。
  • pop() – 从队列首部移除元素。
  • peek() – 返回队列首部的元素。
  • empty() – 返回队列是否为空。
    在这里插入图片描述

示例:
在这里插入图片描述
代码:

  • 解法一
//思路:两个栈进行pop和peek操作
class MyQueue {
    Stack<Integer> s1;
    Stack<Integer> s2;
    /** Initialize your data structure here. */
    public MyQueue() {
        s1 = new Stack<Integer>();
        s2 = new Stack<Integer>(); 
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {	//画图很好理解 给字符串abc 经过两个栈的操作 实际存入栈中元素顺序为bottom[c b a]top
        while (!s1.empty()) s2.push(s1.pop());	//将s1栈中元素都从S1栈放到s2栈中,
        s1.push(x);	//最新进栈的元素放入s1中
        while (!s2.empty()) s1.push(s2.pop());	//再将s2栈中的元素放回s1中
        return;
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return s1.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        int ret = s1.pop();	//
        s1.push(ret);
        return ret; 
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.empty(); 
    }
}

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

  • 解法二
class MyQueue {
    Stack<Integer> s1, s2;
    /** Initialize your data structure here. */
    public MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        s1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while (!s1.isEmpty()) {
            s2.push(s1.pop());	//将S1中的元素进栈到S2中
        }
        int output = s2.pop();
        while (!s2.isEmpty()) { //在恢复S1中元素
            s1.push(s2.pop());
        }
        return output;
    }

    /** Get the front element. */
    public int peek() {	//与pop()思路相同
        while (!s1.isEmpty()) {
            s2.push(s1.pop());
        }
        int output = s2.peek();
        while (!s2.isEmpty()) {
            s1.push(s2.pop());
        }
        return output;
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.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();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值