Linked List Reverse

Reversing a Linked List

Reversing a linked list involves changing the direction of the pointers so that the last node becomes the head and the head becomes the last node.

This operation is fundamental in many algorithms and helps in scenarios where you need to process the list in reverse order without using extra space.

Tip: Reversing a linked list is efficient and can be done in-place with O(1) extra space by manipulating pointers carefully.

Steps to Reverse

  1. Initialize three pointers: previous as null, current as head, and next as null
  2. Iterate through the list until current is null
  3. Store the next node of current in next
  4. Change the next pointer of current to previous
  5. Move previous to current and current to next
  6. After the loop, previous will be the new head of the reversed list

Edge Cases

  • Empty list (head is null)
  • List with only one node
  • List with multiple nodes
  • Handling circular linked lists (should avoid infinite loops)
  • Ensuring no memory leaks or lost references during reversal

Best Practices

  • Use iterative approach for in-place reversal with O(1) extra space
  • Consider recursive reversal for cleaner code but with extra stack space
  • Always check for null pointers to avoid runtime errors
  • Test edge cases like empty or single-node lists
  • Avoid modifying node values; only change pointers

Visualize reversing a linked list step by step

List Node
Current Node
Previous Node
Next Node

List

Generate List to begin

Test Your Knowledge Before Moving Forward!

Reverse Quiz Challenge

How it works:

  • +1 point for each correct answer
  • 0 points for wrong answers
  • -0.5 point penalty for viewing explanations
  • Earn stars based on your final score (max 5 stars)

Linked List Reversal Implementation

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

function reverseList(head) {
  let prev = null;
  let current = head;

  while (current) {
    let next = current.next;
    current.next = prev;
    prev = current;
    current = next;
  }

  return prev;
}