前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用队列实现栈(JAVA)

用队列实现栈(JAVA)

作者头像
用户10921393
发布2024-01-23 09:12:37
890
发布2024-01-23 09:12:37
举报
文章被收录于专栏:Y.

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

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
代码语言:javascript
复制
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();
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-01-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档