user2792523
user2792523

Reputation: 57

Reverse Linked List Using Javascript

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

Upvotes: 0

Views: 90

Answers (1)

Sibtain
Sibtain

Reputation: 108

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

Upvotes: 1

Related Questions