我的目标是创建一个链接列表,其中每个链接都是一个字符。我希望它将一个字符串作为参数,取第一个字母并将其转换为char,然后将其余字符串传递到下一个链接,直到存储整个字符串。这是我到目前为止所做的,虽然我不确定它的哪些部分是正确的或不正确的。我查了一堆例子,这似乎是默认设置。
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.我不确定哪部分代码有错误,我不知道如何修复它。任何帮助都会很棒,谢谢。
答案 0 :(得分:1)
在构造函数head = null中,则在length方法linkedChar curr = null;因此,长度永远不会增加并保持为零。因为while循环不满足条目。
答案 1 :(得分:0)
在您的构造函数中,您永远不会将head
初始化为任何内容,因此在设置linkedChar curr = head;
时,在您的长度方法中,您将curr
设置为null,从而{{1}永远不会在你的while循环中增加。
答案 2 :(得分:0)
您遇到的问题是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());
}
}
祝你好运。