[英]I'm just having hard time understanding the class material from my java class
[英]I'm having a hard time implementing my linked list class
我的目標是制作一個鏈接列表,其中每個鏈接都是一個字符。 我希望它接受一個字符串作為參數,采用第一個字母並將其轉換為字符,然后將字符串的其余部分傳遞到下一個鏈接,直到存儲了整個字符串。 到目前為止,這是我所擁有的,盡管我不確定是哪一部分是正確的還是錯誤的。 我查看了很多示例,這似乎是默認設置。
public class linkedChar{
char data;
linkedChar head;
linkedChar next;
//This is the empty link constructor
public linkedChar(){
next = null;
}
//This is the constructor that takes a string
public linkedChar(String input){
if(input.length() > 0){
data = input.charAt(0);
next = new linkedChar(input.substring(1));
}
}
}
這段代碼可以編譯,但是不能與我的其他操作方法一起使用。 例如,我的長度方法。
public int length(){
int length = 0;
linkedChar curr = head;
while(curr != null){
curr = curr.next;
length++;
}
return length;
}
使用時,返回的長度始終為0。我不確定代碼的哪一部分有錯誤,並且我不知道如何解決。 任何幫助將是巨大的,謝謝。
在構造函數中,head = null,然后在長度方法中,linkedChar curr = null; 因此,長度永遠不會增加,而是保持為零。 因為while循環不滿足輸入條件。
在構造函數中,您永遠不會初始化head
到任何東西,因此在您的length方法中,當您設置linkedChar curr = head;
您將curr
設置為null,因此while循環中的length
永遠不會增加。
您遇到的問題是由於linkedChar head;
因為Java編譯器會為您將值歸零(即,將其設置為null
)。 因此,您的length()
函數將始終在第一輪停止。
一個快速的解決辦法是干脆放棄了linkedChar head
字段設置linkedChar curr
在length()
函數是next
。 這將解決您的問題。
即使您的代碼如下
class Linked{
char data;
Linked next;
//This is the empty link constructor
public Linked(){
next = null;
}
public int length(){
int length = 0;
Linked curr = next;
while(curr != null){
curr = curr.next;
length++;
}
return length;
}
//This is the constructor that takes a string
public Linked(String input){
if(input.length() > 0){
data = input.charAt(0);
next = new Linked(input.substring(1));
}
}
}
public class LinkedChar {
public static void main(String[] args) {
Linked l = new Linked("abcd");
// Here it will print out 4
System.out.println(l.length());
}
}
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.