java中单个链接列表的长度
我创建了一个单链表来查找它的长度,出于某种原因,它只打印1。我定义了java中单个链接列表的长度,java,linked-list,Java,Linked List,我创建了一个单链表来查找它的长度,出于某种原因,它只打印1。我定义了LengthOfLinkedList方法,并试图增加计数器以跟踪链表的长度,但它无法正常工作 public class LengthList { public static int LengthOfLinkedList(List head){ int count = 0; List current = head; while(current != null){ current =
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。谁能告诉我我的代码出了什么问题吗?It选项“长度链接列表:5”。尝试重新编译项目:)您可以使用调试器来调查发生的情况。顺便说一句,手动创建链表和使用非泛型的原因是什么?@user996142在Eclipse中,我做了
Project-->清理
,然后再次运行该项目。它只印了1张。我在eclipse中重新编译是否正确?是的。我不知道为什么是1。使用调试器进行调查:我也得到了5个。为什么不创建一个新文件并复制/粘贴它呢。