algoritmauzmanı
TREN
3.1Singly Linked List
Lesson 3.1.11

Reversing a linked list (iterative)

Reversing a linked list means changing the direction of the links without moving any node. It is one of the most frequently asked linked list questions in interviews, because it tests careful work with . This lesson covers the solution written with a loop (iterative).

What you will learn
  • What each of the three pointers (prev, curr, next) is for
  • Why the rest of the list must be saved before a link is flipped
  • Why the operation takes time and extra memory
7 minTime O(n)Memory O(1)C · Java · Python

1Idea

In the reversed list, the field of every must point to the node that used to come before it. The first node becomes the last and points to ; the old last node becomes the new head. The nodes are reversed in place, with no new memory.

We the list once from start to end and keep three pointers. curr is the node whose link is being flipped. prev is the node the link will point to from now on; it starts as . next saves the rest of the list before the link is flipped.

Each round runs four lines in order: save next, point curr->next at prev, move prev forward, move curr to next. When curr becomes , every link has been flipped and prev points to the old last node. In the last step is moved to that node.

On an empty list the loop never runs and stays . On a one-node list the node's field ends up NULL again. Neither case needs extra code.

2Step by step

The drawing reverses the list 12 → 7 → 3. In each round one link changes direction; the changing link is orange. At each step the matching line of code lights up.

NULL12?7?3?headcurrprev = NULLnext
  1. Start. points to 12; the links run left to right.
  2. prev is and curr is the first node. The first node will be last in the reversed list, so its link must point to NULL.
  3. The loop starts. Before flipping the link, next = curr->next: 7 and everything after it are saved.
  4. The link of 12 is turned to prev, which is . Then prev moves to 12 and curr to 7. We could reach 7 only because of next.
  5. Second round: next saves 3, the link of 7 is turned to 12. prev moves to 7 and curr to 3.
  6. Third round: next saves , the link of 3 is turned to 7. prev moves to 3, curr becomes NULL and the loop ends.
  7. = prev. The old last node, 3, is now the head of the list.
  8. Result: 3 → 7 → 12. No node moved; only the links were turned around.

struct Node {    int data;    struct Node* next;}; void reverse(struct Node** head) {    struct Node* prev = NULL;    struct Node* curr = *head;    while (curr != NULL) {        struct Node* next = curr->next;  // keep the rest        curr->next = prev;               // flip the link        prev = curr;        curr = next;    }    *head = prev;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} Node reverse(Node head) {    Node prev = null;    Node curr = head;    while (curr != null) {        Node next = curr.next;  // keep the rest        curr.next = prev;       // flip the link        prev = curr;        curr = next;    }    return prev;  // the new head}
class Node:    def __init__(self, data):        self.data = data        self.next = None def reverse(head):    prev = None    curr = head    while curr is not None:        next = curr.next  # keep the rest        curr.next = prev  # flip the link        prev = curr        curr = next    return prev  # the new head

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

Each node is visited once and each round does a fixed number of assignments.

Memory
O(1)

However long the list is, only three pointers are used.

The recursive version of the same task also takes time, but each call takes room on the , so it uses O(n) extra memory.

4Common mistake

The most common mistake is not saving next before flipping the link:

curr->next = prev;curr = curr->next;  // now points backwards

As soon as the link is flipped, curr->next points to prev, not to the rest of the list. The second line sends curr backwards; in the first round it becomes and the loop ends. The nodes after 12 can never be reached again. Always write next = curr->next before changing the link.

5Try it

When the loop ends, which pointer points to the new head?

Show the answer

The answer is B. The loop ends when curr becomes . At that moment prev points to the last node processed, which is the old last node. That is why the function returns prev or writes it into .

What happens if this function is called on an empty list (head = NULL)?

Show the answer

The answer is A. curr starts as , so the loop condition is false on the first check. prev is also NULL, so ends up NULL. The empty list needs no extra code.

Lessons you mark show up in the curriculum. This is kept on this device only.