206. Reverse Linked List

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

·

2 min read

/**
 * 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) {

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

  return prev;
};

here are the step-wise visuals for the above solution of reverse linked list function reverseList:

Assuming we have a linked list with the following elements:

1 -> 2 -> 3 -> 4 -> 5 -> null

Step 1: Initialize prev to null and curr to the head of the linked list.

prev = null
curr = 1 -> 2 -> 3 -> 4 -> 5 -> null

Step 2: Loop through the linked list and reverse the next pointer of each node.

while (curr !== null) {
  let next = curr.next;
  curr.next = prev;
  prev = curr;
  curr = next;
}

The first iteration of the loop:

next = 2 -> 3 -> 4 -> 5 -> null
curr.next = null
prev = 1 -> null
curr = 2 -> 3 -> 4 -> 5 -> null

The second iteration of the loop:

next = 3 -> 4 -> 5 -> null
curr.next = 1 -> null
prev = 2 -> 1 -> null
curr = 3 -> 4 -> 5 -> null

The third iteration of the loop:

next = 4 -> 5 -> null
curr.next = 2 -> 1 -> null
prev = 3 -> 2 -> 1 -> null
curr = 4 -> 5 -> null

The fourth iteration of the loop:

next = 5 -> null
curr.next = 3 -> 2 -> 1 -> null
prev = 4 -> 3 -> 2 -> 1 -> null
curr = 5 -> null

The fifth iteration of the loop:

next = null
curr.next = 4 -> 3 -> 2 -> 1 -> null
prev = 5 -> 4 -> 3 -> 2 -> 1 -> null
curr = null

Step 3: Return the prev node, which is the new head of the reversed linked list.

return prev // 5 -> 4 -> 3 -> 2 -> 1 -> null