0

I'm implementing a reversed linked list using Javascript.

var reverseList = function(head) {
    if (!head || !head.next) {
        return head;
      }
      let tmp = reverseList(head.next);
      //head.next = head;
      head.next.next = head;
      head.next = undefined;
      return tmp;
};

The given code is my previous solution, which didn't work. So, I had to go to .next.next element. Why do I need to do it?

Thanks

1 Answer 1

1

If we let the commented line run, it will step back to the previous node. When you did head.next = undefined;, means the last node was the tail of the original list.That is why it would be the head of new reversed list. JavaScript: Reverse a Linked List by Will Vincent

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

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.