~/DHRUVUpskilling
← board/DSA/In place reversal LinkedList/dsa-in-place-reversal-linkedlist-01
Solved·27 Aug

Reverse Linked List

DifficultyMedium
PatternIn place reversal LinkedList
TrackDSA
tl;dr

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

full write-up

Constraints

Let n be the number of nodes in a linked list.

  • 1 ≤ n ≤ 500
  • −5000 ≤ Node.value ≤ 5000

Solution To reverse a LinkedList, we'll store next element of current head. Point our curr.next to prev and update position of prev to curr and curr to next.

function reverse(head) {
  let prev = null;
  let next = null;
  let curr = head;
  
  while (curr !== null) {
    next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  
  head = prev;
  return head;
}