1

I'm trying to reverse a linked list using recursion. Everything goes well until the end and I end up getting broken result.

Can someone tell me what I'm doing wrong?

const reverseLinkedList = (node, newChildOldParent=null ) => {
    if( node.next ){
        reverseLinkedList(node.next, node);
    }
    node.next = newChildOldParent;
    return node;
}

const someList = {
    value: 1,
    next: {
        value: 2,
        next: {
            value: 3,
            next: {
                value: 4,
                next: null
            }
        }
    }
};

console.log(reverseLinkedList( someList ))

I get

{ value: 1, next: null }

Instead of the reversed linked List.

Where am I going wrong?

5
  • 1
    and debugger; too @FrankerZ :) Commented Aug 1, 2018 at 19:45
  • console.log() is forever Commented Aug 1, 2018 at 19:46
  • 2
    your problem is that you are reversing the list alright, but you are getting the first element again in the end (as the stack unfolds). Your first element is now the last and doesn't have a next node. Commented Aug 1, 2018 at 19:58
  • Thanks for the response @Sandro. Appreciate your time. Commented Aug 1, 2018 at 20:41
  • @technoCorner you're welcome :) Commented Aug 2, 2018 at 13:05

1 Answer 1

4

The reversal is working fine, but you've lost track of the new head and instead return the old head which is now pointing to null. Here's a diagram of the stack calls:

curr: 1 next: 2
  curr: 2 next: 3
    curr 3: next: 4
      curr: 4 next: null
      curr: 4 next: 3
    curr: 3 next: 2
  curr: 2 next: 1
curr: 1 next: null <-- uh oh

You need to keep track of the new head, which is node 4. Here's another approach that passes the last node back to the head:

const reverseLinkedList = (curr, prev) => {
    if (curr.next) {
        const newHead = reverseLinkedList(curr.next, curr);
        curr.next = prev;
        return newHead; // pass the new head up the list
    }
    
    curr.next = prev;
    return curr; // base case; return the tail
};

const someList = {
    value: 1,
    next: {
        value: 2,
        next: {
            value: 3,
            next: {
                value: 4,
                next: null
            }
        }
    }
};

console.log(reverseLinkedList(someList));

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

3 Comments

Calling it newHead instead of next might be more appropriate
"the (list of) next nodes", yeah why not. But it is not the next node, so it's confusing.
I see what you're saying here and agree with you--I'll update to clarify.

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.