0

I need to code a method that prints the contents of a linked list recursively, however my method isn't working.

 public LinkedList reverse() {
    LinkedList list = new LinkedList();
    list = reverseRecursion(list, 0);
    return list;
  }
  public LinkedList reverseRecursion(LinkedList list, int pos) {
    if (pos != size()) {
      rotate();
      list.add(get());
      pos = pos + 1;
      reverseRecursion(list, pos);
    }
    return list;
  }

  public String toString() {
    String result = "Contents of list: {";
    result = toStringRecursion(result, 0);
    return result;
  }
  private String toStringRecursion(String result, int pos) {
    if (pos != size()) {
      rotate();
      String temp = result + get().getData() + ",";
      pos = pos + 1;
      toStringRecursion(temp, pos);
    }     
    return result;
  }

the reverse function is working fine, however my toString is only showing up as the initial result "Contents of list: {", despite being passed the previous result as a parameter. If I print the result each time I pass through the toStringRecursion, I can see the desired output right before it reverts back to the inital result when the return line is reached.

2 Answers 2

2

Among other problems with your current approach, you aren't returning the result of the recursive calls to your list:

  private String toStringRecursion(String result, int pos) {
    if (pos != size()) {
      rotate();
      String temp = result + get().getData() + ",";
      pos = pos + 1;

      // Recurse upon the appended String
      return toStringRecursion(temp, pos);
    }     
    // Stop recursing
    return "}";
  }

There's actually much simpler way of approaching this but without seeing your full class definition I can't provide further meaningful feedback without giving a lengthy explanation on linked lists as recursive data structures.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to append the String to the return value. But in this case, using StringBuilder matches what you want to do. That's not good for performance because "+" creates new String instance every time it's called.

      public String toString() {
        StringBuilder sb = new StringBuilder("Contents of list: {");

        appendRecursion(sb, 0);
        return sb.toString();
      }
      private void appendRecursion(StringBuilder result, int pos) {
        if (pos != size()) {
          rotate();
          result.append(get().getData()).append(",");
          pos = pos + 1;
          appendRecursion(result, pos);
        }     
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.