206 Reverse Linked List

Problem Statement

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

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Approach

Three Pointer approach. We first save the next node, then reverse the link, then move previous to current, then move current to next. We return previous as this is the new head of the reversed linked list.

Solution

function reverseLinkedList(head) {
  let current = head;
  let previous = null;
  let next = null;

  while (current !== null) {
    next = current.next;
    current.next = previous;
    previous = current;
    current = next;
  }

  return previous
}

Questions

References

LC