В настоящее время я работаю над своим собственным классом Java LString, который предназначен для преобразования между связанными списками символов и строками.Отслеживание главы ListNode в Java
У меня возникли проблемы с моим методом toString(), в частности, отслеживание «главы» связанного списка, чтобы пропустить его и объединить символы в новую строку. Во время исследования я читал, что должен как-то следить за головой списка, но я не могу понять, как его реализовать.
Любая помощь была бы принята с благодарностью!
Edit: Сообщение об ошибке я получаю это:
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();
}
}
Поскольку ваш вопрос стоит сейчас, нам придется фактически отлаживать ваш код, чтобы узнать, что не так. Вы получаете какой-либо выход ошибки или можете дать конкретную проблему? –
Ваш тест на пустую строку неверен. Если строка пуста, 'original.charAt (0) == 0' выдает исключение, потому что в индексе нет символа. Вы думаете о C? Попробуйте 'original.isEmpty()'. – ajb