2
\$\begingroup\$

Referring to my previous post, should I consider using current pointers for this code snippet for reversing a linked list using recursion?

public static List ReverseRecursion(List head){

        List newHead;
        List current = head;

        if(current == null){
            return null;
        }
        if(current.next == null){
            head = current;
            return head;
        }
        newHead = ReverseRecursion(current.next);
        current.next.next = current;
        current.next = null;
        return newHead;

    }

Or should I consider the solution without using current node as someone pointed out in their solution like this?

public static List ReverseRecursion(List head){
    List newHead;

    if(head == null){
        return null;
    }
    if(head.next == null){
        return head;
    }

    newHead = ReverseRecursion(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
}
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

Extra variable unnecessary

Your variable current in the first code snippet is assigned to head and never changes, so it is unnecessary. You can just use head directly instead, as in the second code snippet. Therefore I feel the second version is superior.

Iterative version

Consider using an iterative version to reverse the list instead of a recursive version. An iterative solution uses \$O(1)\$ space instead of \$O(n)\$ space, and is much easier to understand as well. All you need to do is take each element of the list and add it to the head of a new list, like this:

public static List ReverseList(List head)
{
    List newHead = null;

    while (head != null) {
        List next = head.next;

        head.next = newHead;
        newHead   = head;
        head      = next;
    }
    return newHead;
}
\$\endgroup\$

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.