用队列实现栈(JAVA)

仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false
java 复制代码
class MyStack {
    private Queue<Integer> q1;
    private Queue<Integer> q2;

    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }
    
    public void push(int x) {
       
        if(!q1.isEmpty()) {
            q1.offer(x);
        }else {
            q2.offer(x);
        }
    }
    
    public int pop() {
        if(empty()) {
            return -1;
        }
//找到不为空的队列,转移size-1个元素
        if(!q1.isEmpty()) {
            int size = q1.size();
            for(int i = 0; i < size - 1; i++) {
                q2.offer(q1.poll());
            }
            return q1.poll();
        }else {
            int size = q2.size();
            for(int i = 0; i < size - 1; i++) {
                q1.offer(q2.poll());
            }
            return q2.poll();
        }
    }
    
    public int top() {
        if(empty()) {
            return -1;
        }//"出栈"时出不为空的队列,出size-1个元素,剩下的元素就是要出栈的元素
        if(!q1.isEmpty()) {
            int size = q1.size();
            int tmp = -1;
            for(int i = 0; i < size; i++) {
                tmp = q1.poll();
                q2.offer(tmp);
            }
            return tmp;
        }else {
            int size = q2.size();
            int tmp = -1;
            for(int i = 0; i < size; i++) {
                tmp = q2.poll();
                q1.offer(tmp);
            }
            return tmp;
        }
    }
    
    public boolean empty() {
        return q1.isEmpty() && q2.isEmpty();
    }
}
相关推荐
暮冬-  Gentle°1 小时前
C++中的命令模式实战
开发语言·c++·算法
勾股导航1 小时前
大模型Skill
人工智能·python·机器学习
2501_945423543 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
卷福同学3 小时前
【养虾日记】Openclaw操作浏览器自动化发文
人工智能·后端·算法
春日见4 小时前
如何入门端到端自动驾驶?
linux·人工智能·算法·机器学习·自动驾驶
FreakStudio4 小时前
保姆级 uPyPi 教程|从 0 到 1:MicroPython 驱动包一键安装 + 分享全攻略
python·嵌入式·电子diy
清水白石0084 小时前
Python 对象序列化深度解析:pickle、JSON 与自定义协议的取舍之道
开发语言·python·json
2401_876907524 小时前
Python机器学习实践指南
开发语言·python·机器学习
图图的点云库4 小时前
高斯滤波实现算法
c++·算法·最小二乘法