現在、文字列と文字列のリンクリストを前後に変換するLStringという独自のJavaクラスを作成しています。ListNodeの先頭をJavaで追跡する
私はtoString()メソッドに問題があります。特に、リンクされたリストの "head"を追跡してループし、文字を新しい文字列に連結することに問題があります。調べているうちに、私はリストの頭をどうにかして追跡するはずですが、実装方法を理解できません。
ご協力いただければ幸いです!
編集:私は受けていますエラーメッセージは次のとおりです。
LString.java:79:エラー:シンボルにthis.front =現在
ListNodeを見つけることができません。
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();
}
}
あなたの質問が今立っているので、実際に何が間違っているかを見つけるためにコードをデバッグする必要があります。エラー出力が出ているのですか、それとも特定の問題がありますか? –
空文字列のテストが間違っています。文字列が空の場合、 'original.charAt(0)== 0'はインデックス0に文字がないので例外がスローされます。Cで考えていますか? 'original.isEmpty()'を試してください。 – ajb