Reverse A Singly Linked List Iteratively

Reversing a singly linked list needs three pointers: remember the successor, flip the link, and walk once so prev ends up the new head.

PythonData Integrity

Code

pythonsnippet
35 lines
class Node:
    def __init__(self, value, next=None):
        self.value, self.next = value, next


def build(values):
    head = None
    for value in reversed(values):  # 头插法按原顺序串起来
        head = Node(value, head)
    return head


def reverse(head):
    prev = None
    current = head
    while current:
        nxt = current.next  # 先记住后继,再反指
        current.next = prev
        prev, current = current, nxt
    return prev  # prev 即新头


def show(head):
    out, node = [], head
    while node:
        out.append(str(node.value))
        node = node.next
    out.append('None')
    return ' -> '.join(out)


head = build([1, 2, 3, 4, 5])
print('before:', show(head))
print('after: ', show(reverse(head)))
print('empty: ', show(reverse(None)))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

before: 1 -> 2 -> 3 -> 4 -> 5 -> None
after:  5 -> 4 -> 3 -> 2 -> 1 -> None
empty:  None

Reverse A Singly Linked List Iteratively, line by line

Reverse A Singly Linked List Iteratively keeps everything in the class Node and the functions __init__, build, reverse and show.

The cycling part of this snippet is for value in reversed(values): # 头插法按原顺序串起来.

Caveats

  • Nothing to install — the needed APIs are part of the platform.

Applying it

Entry signature: def build(values)

Output lines are prefixed (before:, after:, empty:), and each label says which step emitted that line.

build is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

def __init__(self, value, next=None):
    self.value, self.next = value, next
def build(values):
    head = None
    for value in reversed(values):  # 头插法按原顺序串起来
        head = Node(value, head)
    return head
def reverse(head):
    prev = None
    current = head
    while current:
        nxt = current.next  # 先记住后继,再反指
        current.next = prev
        prev, current = current, nxt
    return prev  # prev 即新头

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `__init__`, `build`, `reverse` at load time.