用队列实现栈(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();
    }
}
相关推荐
.Cnn6 小时前
Maven进阶知识点
java·maven
布朗克1686 小时前
11 面向对象思想入门
java·对象
袋鼠云数栈6 小时前
数栈 V7.0 多模态数据智能平台:打造 AI-Ready 的企业数据底座
大数据·数据结构·数据库·人工智能·数据治理·多模态
gCode Teacher 格码致知6 小时前
Python教学:字符编码的四种环境-由Deepseek产生
开发语言·python
拽着尾巴的鱼儿6 小时前
lombok.RequiredArgsConstructor bean 注入
java·lombok
铁链鞭策大师6 小时前
JavaEE之多线程
java·开发语言·java-ee
摇滚侠6 小时前
Maven 入门+高深 jar 包冲突 167-171
java·maven·jar
我是唐青枫6 小时前
Java Optional 实战指南:优雅处理空值与链式转换
java·开发语言
摇滚侠6 小时前
SpringBoot 升级,依赖冲突如何解决
java·spring boot·spring
jack@london6 小时前
eclipse启动tomcat6时报错OutOfMemoryError: PermGen space
java·ide·eclipse