Back to solutions

Reverse Linked List

EasyLinked List

Reverse a singly linked list and return the new head.

Constraints
  • 0 <= list length <= 5000
  • -5000 <= Node.val <= 5000

Iterative pointer reversal

Time O(n)Space O(1)

Walk the list, reversing each next pointer to point at the previous node while keeping a reference to the rest of the list.

struct ListNode { int val; ListNode* next; };

ListNode* reverseList(ListNode* head) {
    ListNode* prev = nullptr;
    while (head) {
        ListNode* nxt = head->next;
        head->next = prev;
        prev = head;
        head = nxt;
    }
    return prev;
}