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.
Code
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: NoneReverse 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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.