用队列实现栈(JAVA)

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

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

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();
    }
}

版权声明:本文为博主作者:咸鱼云!原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/weixin_69762204/article/details/135315539

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2024年1月16日
下一篇 2024年1月16日

相关推荐