lauraxx
lauraxx

Reputation: 1

How to write a recursive toString method for linked list in java

I'm trying to write a toString method for my linked list stack in java. I have a stack class and a node class. I created a node in the stack class to implement the push/pop methods. Now I'm just having trouble printing out my linked list. The method I have written below only prints out the first 2 elements in my linked list...

public class StackList<E> implements Stack<E> {
protected Node stackList;

public StackList() 
{ 
    stackList = new Node();
    stackList.next = null;
}


public String toString() 
{
    if (stackList.next == null)
    {
        return (String) stackList.value;
    }
    else
    {
        return stackList.value + " ; " + stackList.next.value.toString();
    }

}

Upvotes: 0

Views: 4754

Answers (1)

Alex Gittemeier
Alex Gittemeier

Reputation: 5373

Instead of using recursion, I would suggest something like this:

public String toString() {
    Node curNode = stackList.next;
    StringBuilder ret = new StringBuilder(stackList.value);
    while (curNode != null) {
        ret.append("; " + curNode.value);
        curNode = curNode.next;
    }
    return ret.toString();
}

Recursion version: (totally unintended rhyming)

public String toString() {
    return getAfterString(stackList);
}

private String getAfterString(Node node) {
    if (node.next != null) {
        return node.value + "; " + getAfterString(node.next);
    }
    else {
        return (String) node.value;   
    }
}

Upvotes: 1

Related Questions