数据结构——队列

什么是队列?

队列是一种基于先进先出的数据结构,是一种只能在一端进行插入,另一端进行删除的特殊线性表,按照先进先出的原则存储数据。

手写队列

package com.hzrc.hrmanagement.dataStructure;

/**
 * @author SJT
 * @Description: 队列
 * @date 2022-06-22 10:45
 */
public class MyQueue<T> {

    //容量大小
    private Integer size;

    //头结点
    private Node head;

    //尾节点
    private Node tail;

    public MyQueue() {

        head = new Node(null,null);
        size = 0;
    }

    //集合大小
    public Integer getMyQueueSize() {

        return size;

    }

    //存值
    public boolean add(T addData) {

        if(tail == null) {
            tail = new Node(addData,null);
            head.next = tail;

        }else {
            Node newNode = new Node(addData, null);
            tail.next = newNode;
            tail = newNode;
        }

        size++;
        return true;
    }

    //取值
    public T poll() {

        if(head.next == null) {
            return null;
        }

        Node old = head.next;
        head.next = old.next;
        size--;

        return old.getValue();
    }


    class Node {

        private T value;

        private Node next;

        public Node(T value, Node next) {
            this.value = value;
            this.next = next;
        }

        public T getValue() {
            return value;
        }

        public void setValue(T value) {
            this.value = value;
        }

        public Node getNext() {
            return next;
        }

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


}

测试队列

package com.hzrc.hrmanagement.dataStructure;

/**
 * @author SJT
 * @Description:
 * @date 2022-06-22 11:03
 */
public class TestMyQueue {

    public static void main(String[] args) {

        MyQueue<String> myQueue = new MyQueue();
        myQueue.add("test1");
        myQueue.add("test2");
        myQueue.add("test3");
        System.out.println(myQueue.poll());
        System.out.println("size:"+myQueue.getMyQueueSize());
        System.out.println(myQueue.poll());
        System.out.println("size:"+myQueue.getMyQueueSize());
        System.out.println(myQueue.poll());
        System.out.println("size:"+myQueue.getMyQueueSize());


    }

}

测试结果

在这里插入图片描述




知是行之始,行是知之成!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值