gpt4 book ai didi

java - 在Java中跟踪ListNode的头

转载 作者:行者123 更新时间:2023-12-01 09:54:02 25 4
gpt4 key购买 nike

我目前正在开发自己的名为 LString 的 Java 类,该类旨在在字符链接列表和字符串之间来回转换。

我的 toString() 方法遇到问题,特别是跟踪链接列表的“头”,以便循环遍历它并将字符连接到新字符串中。在研究时,我读到我应该以某种方式跟踪列表的头部,但我不知道如何实现它。

任何帮助将不胜感激!

编辑:我收到的错误消息是:

LString.java:79: 错误:找不到符号
ListNode 当前 = this.front;

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();

}





}

最佳答案

通过追加到末尾来构建链表的一般模式是:

开头:

head = null;
tail = null;

要将 newNode 添加到列表中:

if (head == null) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;

我认为您正在尝试通过在列表类中仅保留一个指针来实现此目的,但这效果不太好。另外,使用此模式执行操作意味着您不必在列表前面有一个“特殊”节点,除非有其他充分的理由。看起来您试图使用不带参数的 new ListNode() 来创建某种特殊节点,但只是有时。这是不必要的,只会让事情变得更加复杂。

关于java - 在Java中跟踪ListNode的头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37381427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com