java链表实现单链表常见操作

package algorithrm;

public class LinkList<T>{
    private Node head;
    private int N;

    public class Node<T>{
        public T val;
        public Node next;

        public Node(T val, Node next) {
            this.val = val;
            this.next = next;
        }
    }
//初始化
    public LinkList(){
        this.head = new Node(null, null);
        this.N=0;
    }
//    获取头结点
    public Node gethead()
    {
        return this.head;
    }
    public void clear()
    {
        this.head=null;
        this.N=0;
    }
//    链表长度
    public int length()
    {
        return this.N;
    }

    public T get(int i)
    {
        Node n = head.next;
        for(int index=0;index<i;index++)
        {
            n=n.next;
        }
        return (T) n.val;
    }
    public void insert(T t)
    {
        Node n = head;
        while(n.next!=null)
        {
            n=n.next;
        }
        Node newnode = new Node(t,null);
        n.next =newnode;
        this.N++;
    }
    public void inserttotail(T t)
    {
        Node<T> tNode = new Node<>(t, null);
        tNode.next = head.next;
        head.next=tNode;
        this.N++;
    }
    public void insert(T t,int i)
    {
        //i位置前一个节点
        Node pre = head;
        for(int index =0;index<=i-1;index++)
        {
            pre=pre.next;
        }
//        创建新节点
        Node newnode = new Node(t,pre.next);

        pre.next=newnode;
//        元素加1
        this.N++;
    }
    public T remove(int i)
    {
        Node pre = head;
        for(int index =0;index<=i-1;index++)
        {
            pre=pre.next;
        }
//        i位置的节点
        Node curr = pre.next;

        Node newnode = curr.next;

        pre.next=newnode;
        this.N--;
        return (T)curr.val;
    }
    public int indexogf(T t)
    {
        Node n = head;
        int i =0;
        while(n.next!=null)
        {
            if(n.val==t)
                return i;
            n=n.next;
            i++;
        }
        return -1;
    }
}

你可能感兴趣的:(数据结构,链表,java,算法,单链表)