在Java中跟踪ListNode的头部
我目前正在开发自己的名为LString的Java类,该类用于在字符和字符串的链接列表之间来回转换
我的toString()方法有问题,特别是跟踪链表的“头”,以便循环遍历它并将字符连接到新字符串中。在研究过程中,我读到我应该以某种方式跟踪列表的开头,但我不知道如何实现它
任何帮助都将不胜感激
编辑:我收到的错误消息是:
伊斯特林。java:79:错误:找不到符号
ListNode current=这个。前线
public class LString{
private static int length;
// ListNode constructors
// Creates a new ListNode with characters stored in variable "data" and
// Node named next
private class ListNode{
char item;
ListNode next;
private ListNode(){
}
// creates a new ListNode that has the value and links to the specified ListNode
private ListNode(char item, ListNode next){
this.item = item;
this.next = next;
}
// given a character, creates a new ListNode that doesn't link to anything
private ListNode(char item){
this.item = item;
this.next = null;
}
}
public LString(){
this.length = 0;
ListNode front = new ListNode();
}
//LString
// Takes in a String object and loops until it has added all characters to a new linked list
public LString(String original){
ListNode front;
this.length = 1; // length keeps track of number of nodes
if (original.charAt(0) == 0){ // creates a new ListNode if it is an empty string
front = new ListNode();
}
else {
front = new ListNode(original.charAt(0));
}
//System.out.println("this is happening " + front.item);
//ListNode current = front;
for (int index = 1; index < original.length(); index++) {
front.next = new ListNode(original.charAt(index), front.next);
front = front.next;
//System.out.println("strings: " + front.item);
length++;
}
//System.out.println("length: " + length);
}
// returns length of the LString object
public int length(){
return this.length;
}
// toString takes an LString object and converts it to a string
public String toString(){
StringBuilder newString;
ListNode current = this.front;
while (current.next != null){
newString.append(current.item);
current = current.next;
}
return newString.toString();
}
public static void main(String[] args){
LString stuffTest = new LString("hello");
int valueOf = stuffTest.length();
System.out.println(stuffTest.length());
String testMeWhy = stuffTest.toString();
}
}
# 1 楼答案
您的基本问题是,应该只有一个
front
,它应该是类成员,而不是局部变量。这就是LString
类“跟踪”第一个节点的方式这将让你开始并允许你维护实际的列表。您的其他
LString
方法也需要一些工作,但是一旦您解决了这个问题,您应该能够使用调试器逐步完成代码并自己解决剩余的问题# 2 楼答案
通过追加到末尾来构建链表的一般模式是:
一开始:
要将
newNode
附加到列表中:我认为你试图通过在list类中只保留一个指针来实现这一点,但效果并不好。此外,使用这种模式进行操作意味着不必在列表的前面有一个“特殊”节点,除非有其他好的理由。看起来您试图在没有参数的情况下使用
new ListNode()
来创建某种特殊节点,但只是偶尔使用。这是不必要的,只会让事情变得更复杂