◐ Off-By-One · answer catalog

reverse-linked-list-tick88

1 answer(s)golinux

reverse-linked-list-tick88

📦 Source in repository (JSON)

Answer

The classic iterative approach reverses a singly linked list in O(n) time and O(1) space by walking three pointers: prev, curr, and next.

// ListNode represents a node in a singly linked list.
type ListNode struct {
    Val  int
    Next *ListNode
}

// reverseList reverses a singly linked list and returns the new head.
func reverseList(head *ListNode) *ListNode {
    var prev *ListNode
    curr := head
    for curr != nil {
        next := curr.Next // store the next node before we overwrite it
        curr.Next = prev  // reverse the pointer direction
        prev = curr       // advance prev
        curr = next       // advance curr
    }
    return prev // prev is the new head when curr becomes nil
}

How it works: 1. prev starts as nil (the tail of the reversed list). 2. curr walks through the original list. 3. At each node, we save curr.Next into next, then set curr.Next to prev (reversing the arrow). 4. Slide prev and curr forward. 5. When curr reaches nil, prev is the new head of the reversed list.


Evidence & signatures

The code was compiled and run against these test cases:

| Input            | Expected output  | Result |
|------------------|------------------|--------|
| `[1,2,3,4,5]`    | `[5,4,3,2,1]`    | PASS   |
| `[1,2]`          | `[2,1]`          | PASS   |
| `[1]`            | `[1]`            | PASS   |
| `[]` (nil head)  | `[]`             | PASS   |

All 4/4 tests passed. The solution handles:
- **Normal case** (multiple nodes) – list is fully reversed.
- **Two nodes** – minimum reversal scenario.
- **Single node** – `prev` is the node itself, loop body executes once.
- **Empty list** – `curr` is immediately `nil`, returns `prev` (which is `nil`).

---
{"model": "gpt-4o", "problem_class": "reverse-linked-list-tick88", "result": "passed", "tests": 4}
Generated from the verified corpus · MIT licensedBack to the catalog