单向链表的数据结构实现代码

/**
 * @author: yekai  <br/>
 * Date: 2021/11/16:0:30  <br/>
 * Description:单向链表的数据结构实现
 */
public class LinkList<T> {
    //头结点
    private Node head;
    //记录链表的长度
    private int N;

    private class Node {
        //元素
        private T item;
        //指向下一个节点
        Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
    //初始化头结点,构造器
    public LinkList(){

        this.head = new Node(null,null);
        this.N = 0;
    }
    //清空链表
    public void clear(){
        head.next = null;
        this.N = 0;
    }

    //判断链表是否为空,空返回true,非空返回false
    public boolean isEmpty(){
        //直接返回长度是否等于0即可
        return N==0;
    }
    //获取链表中元素的个数
    public int length(){
        return N ;
    }
    //读取并返回链表中第i个元素的值
    public T get(int i){
        Node n = head.next;
        //通过循序从头结点依次往后找,依次找i次即可找对对应的元素
        for (int index = 0; index < i; index++) {
            //循环i次即可找到对应的结点
            n = n.next;
        }

        return n.item;
    }
    //往链表中增加一个元素
    public void insert(T t){
        //找到当前最后一个结点
        Node n = head;
        while (n.next != null){
            n = n.next;
        }
        //创建一个新的结点
        Node now = new Node(t,null);
        //最后一个结点指向now
        n.next = now;
        //链表节点数+1
        N ++;
    }
    //在链表中第i个元素之前插入一个值为t的元素
    public void insert(int i, T t){
        //遍历到i之前的一个结点
        Node n = head;
        for (int index = 0; index < i-1; index++) {
            n = n.next;
        }
        //遍历到i结点
        Node iNode = n.next;
        //新建一个结点t,他的next结点指向i结点
        Node nowNode = new Node(t,iNode);
        //修改i-1的结点的next指向t
        n.next = nowNode;
        //结点数加+1
        N++;
    }
    //删除并返回链表中第i个数据元素
    public T remove(int i){
        //找到i-1个结点,修改他的结点指向i+1即可
        Node n = head;
        for (int index = 0; index < i-1; index++) {
            n = n.next;
        }
        T removeNode = n.next.item;
        n.next = n.next.next;
        N--;
        return removeNode;
    }
    //返回链表中首次出现的指定数据元素的序号,若不存在,返回-1
    public int indexOf(T t){
        Node n = head;
        if(n.item!=t){

            for (int index = 0; n.next!=null; index++) {
                n = n.next;
                if(n.item.equals(t)){
                    return index;
                }
            }
            return -1;
        }return 1;

    }

}

 

posted @ 2021-11-16 13:59  yekaiIT  阅读(35)  评论(0编辑  收藏  举报