Java单链表实现

//线性表之单链表自实现  (JDK链表:LinkedList)
public class LinkList<T> {
    //定义头结点
    private Node head;
    //记录链表长度
    private int N;
    //内部节点类
    private class Node{
        //节点存储的数据
        T data;
        //该节点的下一个节点
        Node next;

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

    public LinkList(){
        this.head=new Node(null,null);
        this.N=0;
    }
    //向链表中新增元素
    public void add(T e){
        Node node = new Node(e,null);
        Node n=head;//n引用head对象
        //n的引用指向head的下一个节点
        while (n.next!=null){
            n=n.next;
        }
        n.next=node;
        N++;
    }

    //中间插入节点
    public void insert(int i,T e){
        Node n=head;
        //找到第i个节点的前一个节点
        for (int a=0;a<i-1;a++){
            n=n.next;
        }
        //创建新节点指向原理i位置的节点
        Node node1 = new Node(e, n.next);
        //原来i位置之前的节点指向新节点
        n.next=node1;
        N++;
    }

    public void clear(){
        head.next=null;
        N=0;
    }

    //删除指定位置i的节点
    public T remove(int i){
        Node n=head;
        //找到i之前的一个节点
        for (int a=1;a<i;a++){
            n=n.next;
        }
        T s=n.next.data;
        n.next=n.next.next;
        N--;
        return s;
    }

    public int indexOf(T t){
        Node n=head.next;
        for (int i = 1; i <= N; i++) {
            if (n.data.equals(t)){
                return i;
            }
            else
                n=n.next;
        }
        //如果没有找到,返回-1
        return -1;
    }

    public void out(){
        Node node=head;
        for (int i=0;i<N;i++){
            System.out.println(node.next.data);
            node=node.next;
        }
    }
    //递归使所有节点反转
    public Node reverse(Node n){
        if (n.next==null){
            head.next=n;
            return n;
        }

        reverse(n.next);
        n.next.next=n;
        n.next=null;
        return n;
    }

    //单链表反转
    public void reverse(){
        if (head.next==null){
            return;
        }else
            reverse(head.next);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值