java中单链表的长度

时间:2015-11-10 21:29:33

标签: java linked-list

我创建了一个单独的链接列表来查找它的长度,由于某种原因它只打印1.我定义了LengthOfLinkedList方法,我试图增加计数器以跟踪链接的长度列表,但它无法正常工作。

public class LengthList {



public static int LengthOfLinkedList(List head){

    int count = 0;
    List current = head;
    while(current != null){
        current = current.next;
        count++;
    }
    return count;
}



    public static void main (String[] args){

        List myList = new List(1);
        myList.next = new List(2);
        myList.next.next = new List(3);
        myList.next.next.next = new List(4);
        myList.next.next.next.next = new List(5);


        System.out.println("\n Length LinkedList : \n"+LengthOfLinkedList(myList));
    }
}

class List {
    int value;
    List next;
    public List(int k){
        value = k;
        next = null;
    }

    public String toString(){

        List cur = this;
        String output = "";
        while(cur != null){

            output+=cur.value+"-->";
            cur = cur.next;
        }
        return output+"Tail";
    }
}

打印长度仅为01.有人能告诉我我的代码有什么问题吗?

0 个答案:

没有答案