Java链表实现队列

问题:用链表实现一个先进先出的队列

分析:

1、链表实现,必须有一个节点能够装数据和下一个节点的指针(引用)

2、队列必须要有队首、队尾指针和记录当前队列大小的整型数

3、入队:往队尾加,队尾的下一个指针指向新元素,随后移动队尾指针指向新元素

4、出队:取出队首数据,移动队首指针指向队首的下一个元素

5、边界问题考虑

实现

1、节点类 

/**
 * 队列结点
 *
 * @author zab
 * @date 2021-01-27 11:13
 */
public class Node {
    private Node next;
    private Object object;

    public Node(Node next, Object object) {
        this.next = next;
        this.object = object;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }
}

2、队列类


/**
 * 简单队列
 *
 * @author zab
 * @date 2021-01-27 11:03
 */
public class MyQueue {
    private Node head;
    private Node tail;
    private int size;

    public MyQueue() {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    public boolean in(Object o) {
        //1、队列没有元素的情况
        if (size == 0) {
            head = new Node(null, o);
            tail = head;
            size++;
            return true;
        }
        //2、如果队列有元素
        Node newTailNode = new Node(null, o);
        tail.setNext(newTailNode);
        tail = newTailNode;
        size++;
        return true;
    }

    public Object out() {
        //1、队列没有元素的情况
        if (size == 0) {
            return null;
        }
        //2、如果队列有1个元素
        if (size == 1) {
            Object o = head.getObject();
            head = tail = null;
            size--;
            return o;
        }
        Object o = head.getObject();
        head = head.getNext();
        size--;
        return o;
    }

    public int getSize() {
        return size;
    }
}

3、测试类

public class MyQueueTest {
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.in(1);
        myQueue.in(2);
        myQueue.in(3);
        myQueue.in(4);

        Object out = myQueue.out();
        Object out1 = myQueue.out();
        Object out2 = myQueue.out();
        Object out3 = myQueue.out();
        Object out4 = myQueue.out();

        System.out.println(out);
        System.out.println(out1);
        System.out.println(out2);
        System.out.println(out3);
        System.out.println(out4);
    }
}

4、结果

1
2
3
4
null

Process finished with exit code 0

 可以看到,一个元素出队后,队列是2-->3-->4-->null

只剩最后一个元素时,是head和tail都指向4

 当全部出队的时候,head和tail都指向null,这里得益于只有一个节点的出队方法边界处理。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值