链表之外的字符串,对象的高效构造函数

Strings out of Linked Lists, efficient constructor for an object

我正在努力在名为 LString 的对象中构建链表构造函数。构造函数从链表而不是数组构建字符串。另一个文件测试该对象以验证其能力,当我使用我的构造函数 运行 该文件和 toString() 方法时,我收到此错误:

Running constructor, length, toString tests (10 tests)
Starting tests: ..FF......
Time: 0.00

2 failures:
1) t02aEmptyConstructorIsEmptyString(LStringTest$EmptyStringTest)
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        ... 1 more
        at LString.<init>(LString.java:45)
        at LStringTest$EmptyStringTest.t02aEmptyConstructorIsEmptyString(LStringTest.java:193)
        ... 9 more
2) t02bEmptyConstructorHasZeroLength(LStringTest$EmptyStringTest)
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        ... 1 more
        at LString.<init>(LString.java:45)
        at LStringTest$EmptyStringTest.t02bEmptyConstructorHasZeroLength(LStringTest.java:198)
        ... 9 more

Test Failed! (2 of 10 tests failed.)

我相信我正确地构建了链接列表,并且错误地创建了 LString 对象,尽管我很难找出原因。任何建议表示赞赏,努力学习 java.

这是我的代码:

public class LString    {

     node front;
     int size;

     private class node {
          char data;
          node next;

          public node (){
          }

          public node (char newData){
                this.data = newData;
          }

          public node (char newData, node newNext){
                this.data = newData;
                this.next = newNext;
          }


     }

     public LString(){
          this.size =   0;
          this.front =  null;
     }
     public LString(String original)    {
          this.size = original.length();
          this.front =  new node(original.charAt(0));
          node curr = this.front;

          for   (int i =1; i <  original.length(); i++) {
                curr.next = new node(original.charAt(i));
                curr = curr.next;

          }


     }
    public String toString(){
        StringBuilder result = new StringBuilder();

        node curr = front;
        while (curr != null){

            result.append(curr.data);
            curr = curr.next;
        }
        return result.toString();
    }
}

当您将空字符串传递给第二个构造函数时会发生这种情况。在这种情况下,以下行会引发异常。

this.front =  new node(original.charAt(0));

因为chatAt(0)不存在(0超出范围)。您可以使用 if 条件来保护此构造函数以防止这种情况发生。