LinkedLists,为自定义链表类构建toString方法

时间:2015-03-02 01:18:41

标签: java linked-list tostring

我正在努力在名为toString()的链接列表中完成此LString方法

该类创建一个LString对象,该对象使用链接列表而不是数组来模仿String和StringBuilder。它从链表中创建字符串。

以下是该方法的代码:

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


    node curr = front;
    while   (curr   !=  null){
        result.append(curr.data);
        curr = curr.next;

    }


    return result.toString();
}

我尝试了几种不同的东西,我想我已经接近搞清楚了。但是我不能从这个错误信息中继续前进:

Running constructor, length, toString tests (10 tests)
Starting tests: .......E.E
Time: 0.009

There were 2 failures:
1) t11aLStringOfStringToString[1](LStringTest$LStringOfStringTest)
org.junit.ComparisonFailure: LString("ab").toString() is wrong. expected:<[a]b> but was:<[]b>
        at org.junit.Assert.assertEquals(Assert.java:115)
        at LStringTest$LStringOfStringTest.t11aLStringOfStringToString(LStringTest.java:221)
        ... 10 more
2) t11aLStringOfStringToString[2](LStringTest$LStringOfStringTest)
org.junit.ComparisonFailure: LString("This is a long string.").toString() is wrong. expected:<[This is a long string].> but was:<[].>
        at org.junit.Assert.assertEquals(Assert.java:115)
        at LStringTest$LStringOfStringTest.t11aLStringOfStringToString(LStringTest.java:221)
        ... 10 more

Test Failed! (2 of 10 tests failed.)

Test failures: abandoning other phases.

LString类使用另一个类LStringTest.java进行各种测试。此错误消息来自运行LStringTest.java,但我正在处理的方法是在LString中。它是LString("ab").toString() is wrong位。

对于某些情境,这是我班上的其余部分:

public class LString    {

     // 2. Fields
     node   front;
     //node tail;
     int size;

     // 1. Node class

    private class node {

        char data;
        node next;

        //constructors
        //1. default
        public node (){
        }

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

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


   }
     // 3. Constructors
    public LString(){
        this.size = 0;
        this.front = null;
    }
   public LString(String original) {

      for (int i =0; i < original.length(); i++) {

         this.front = new node(original.charAt(i));
      }
      this.size = original.length();

   }

    //  4.  Methods
   public int length() {
      return this.size;
   }
   public int compareTo(LString anotherLString) {
      return 0;
   }
   public boolean equals(Object other) {
      if (other == null || !(other instanceof LString)) {
         return false;
      }
      else {
         LString otherLString = (LString)other;
         return true;
      }
   }
   public char charAt(int index) {
      return 'a';
   }
   public void setCharAt(int index, char ch) {
      ch = 'a';
   }
   public LString substring(int start, int end) {
      return null;
   }
   public LString replace(int start, int end, LString lStr) {
      return null;
   }

    //append
    public void append(char data){

        this.size++;

        if  (front == null){
             front =    new node(data);
             return;
        }

        node curr = front;
        while   (curr.next != null){
             curr   = curr.next;
        }

        curr.next = new node(data);

    }

    //prepend
    public void prepend (char data){
        /*node temp = new   node(data);
        temp.next = front;
        front   = temp;*/

        front   = new   node(data, front);
        size++;
    }

    //delete
    public void delete(int index){
    //assume    that index is valid
        if  (index == 0){
             front =    front.next;
        } else {
             node   curr = front;
             for (int i = 0; i <    index   - 1; i++){
                curr = curr.next;
             }
             curr.next = curr.next.next;
        }
        size--;

    }

    //toString
    public String toString(){
        StringBuilder result    = new   StringBuilder();
        //result.append('[');

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

         //result.append('[');
            result.append(curr.data);
         curr = curr.next;
         //result.append(']');
            //if (curr.next != null){

            //}

        }

        //result.append(']');
        return result.toString();
    }

    //add   (at an index)
    public void add(int index,  char data){
         if (index == 0){
              front = new node(data, front);
         }  else {
              node curr = front;
              for   (int i =    0;  i < index - 1;  i++){
                    curr = curr.next;
              }
              curr.next = new   node(data, curr.next);
         }
     }
}

2 个答案:

答案 0 :(得分:1)

在LString构造函数中,每次循环时,只会将一个新char重新分配给前面。当它完成构造LString时,它只有原始String中最后一个char的一个前节点。

您可以在循环外部分配前面并创建一个临时“当前”节点以进行移动并分配字符。像这样:

//This will assign the first char to the front
this.front = new node(original.charAt(0);

//Create a temporary current node
node curr = this.front;

//Since you already have the first node set up you can start i at 1
for (int i = 1; original.length(); i++) {

   //Assign the char to the next node
   curr.next = new node(original.charAt(i));

   //Change current to the next node, this way it wont just rewrite the same node
   curr = curr.next;

}

就我所知,这是主要问题,因此toString方法本身没有任何问题。

希望这有帮助,祝你好运。

答案 1 :(得分:0)

我看到的最大问题是你的LString构造函数在为新字符串生成节点时使用了错误的节点构造函数。结果,链表节点实际上没有彼此链接。基本上你需要改变

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

this.front = new node(original.charAt(i), this.front);

当然,您仍然会this.front指向最后一个字符,而不是第一个字符,因此您可能希望更改解析输入的顺序。另一个可能更好的选择是在构造函数中使用您自己的append方法来避免代码重复。但是,现在它的实现方式,你最终会得到一个O(n ^ 2)算法,因为每个追加都会迭代整个列表。

显然很多LString的其余部分也未实现(charAt总是返回&#39; a&#39; ...),所以这不是你唯一的问题。