Lesson 11 of 14

Reverse a List

Reversing a Linked List In-Place

To reverse a list, walk through it and flip each next pointer to point backward. You need three pointers: prev, cur, and next.

struct Node *reverse(struct Node *head) {
    struct Node *prev = NULL;
    struct Node *cur = head;
    while (cur != NULL) {
        struct Node *next = cur->next;
        cur->next = prev;
        prev = cur;
        cur = next;
    }
    return prev;
}

Step-by-Step

Initial: NULL <- ? [1] -> [2] -> [3] -> NULL
         prev   cur

Iteration 1:
  next = cur->next   → [2]
  cur->next = prev   → [1] -> NULL
  prev = cur         → [1]
  cur = next         → [2]

Iteration 2:
  next = cur->next   → [3]
  cur->next = prev   → [2] -> [1] -> NULL
  prev = cur         → [2]
  cur = next         → [3]

Iteration 3:
  next = cur->next   → NULL
  cur->next = prev   → [3] -> [2] -> [1] -> NULL
  prev = cur         → [3]
  cur = next         → NULL  ← loop ends

Return prev → [3] (new head)

Your Task

Implement struct Node *reverse(struct Node *head) that reverses the list in-place and returns the new head.

TCC compiler loading...
Loading...
Click "Run" to execute your code.