SimuVedaAlgorithms Lab Open in the lab

Lists, stacks & queues / Beginner

Reverse a Linked List Visualizer

Walk the list once. At each node, save next, point the node back to prev, then move prev and curr one step forward.

Start the Reverse a Linked List simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.

Time and space complexity

Best timeO(n)
Average timeO(n)
Worst timeO(n)
Extra spaceO(1)

Worked example, step by step

The same steps the simulator shows, on a small input.

  1. prev starts at null and curr at the head (1).
  2. Save next = 2 so the rest of the list is not lost.
  3. Point 1 back to null.
  4. Move prev to 1 and curr to 2.
  5. Save next = 3 so the rest of the list is not lost.
  6. Point 2 back to 1.
  7. Move prev to 2 and curr to 3.
  8. Save next = 4 so the rest of the list is not lost.
  9. Point 3 back to 2.
  10. Move prev to 3 and curr to 4.
  11. Save next = 5 so the rest of the list is not lost.
  12. Point 4 back to 3.
  13. Move prev to 4 and curr to 5.
  14. Save next = null so the rest of the list is not lost.
  15. Point 5 back to 4.
  16. Move prev to 5 and curr to null.
  17. curr is null, so we are done. The new head is 5.

Try it with your own input →

Reverse a linked list in Java, Python, C++, C and JavaScript

ListNode reverseList(ListNode head) {
  ListNode prev = null, curr = head;
  while (curr != null) {
    ListNode next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}
def reverse_list(head):
    prev, curr = None, head
    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt
    return prev
ListNode* reverseList(ListNode* head) {
  ListNode *prev = nullptr, *curr = head;
  while (curr) {
    ListNode* next = curr->next;
    curr->next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}
struct ListNode* reverseList(struct ListNode* head) {
  struct ListNode *prev = NULL, *curr = head;
  while (curr) {
    struct ListNode* next = curr->next;
    curr->next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}
function reverseList(head) {
  let prev = null, curr = head;
  while (curr !== null) {
    const next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}

In an interview

LeetCode 206, Reverse Linked List.

Draw the three pointers before writing code. Most bugs come from changing curr.next before saving it.

More lists, stacks & queues