22 April 2024

Easy

206. Reverse Linked List (R)

Link: https://leetcode.com/problems/reverse-linked-list

Description: Given the head of a singly linked list, reverse the list, and return the reversed list.

Solution:

The recursive function reverseList is designed to reverse a singly linked list. It operates by diving deep into the list until it reaches the last node or an empty list (base case). At this point, it starts to backtrack, reversing the direction of the links between nodes one by one. Specifically, for each node (starting from the end back to the beginning), it sets the next pointer of the next node to point back to itself, effectively reversing the link. This reversal process continues until it returns to the start of the list, at which point all nodes have been reconnected in reverse order. The originally last node now becomes the head of the new reversed list, which is then returned by the function.

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function (head) {
  if (head === null || head.next === null) {
    return head
  }
  const newHead = reverseList(head.next)
  head.next.next = head
  head.next = null
  return newHead
}