用队列实现栈(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();
    }
}
相关推荐
ZhengEnCi3 小时前
M3-markconv库找不到wkhtmltopdf问题
python
2301_764441335 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI5 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
014-code5 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
Billlly6 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives6 小时前
atcoder ABC 452 题解
数据结构·算法
chushiyunen6 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA6 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
feifeigo1236 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
baidu_huihui6 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip