Given the head of a singly linked list, reverse it and return the new head.
Example
Input: 1 2 3 4 5
Output: 5 4 3 2 1
Approach
Walk the list once, rewiring each node's next pointer to point backward to the previous node instead of forward. The classic trap: you must save a reference to the next node before overwriting current.next, or you lose the rest of the list permanently.
Save next=2, point 1.next backward to prev (None), then advance prev and curr.
Input format
Line 1: the list values, space-separated
Print the reversed list, space-separated.
Not solved yet
Ctrl+Enter
Editor
classListNode:
def__init__(self, val=0):
self.val = val
self.next = Nonedefbuild_list(values):
ifnot values:
returnNone
head = ListNode(values[0])
curr = head
for v in values[1:]:
curr.next = ListNode(v)
curr = curr.nextreturn head
values = list(map(int, input().split()))
head = build_list(values)
# TODO: iterative reversal — save next BEFORE overwriting current.next
prev, curr = None, head
Input (stdin)
Output
Run your code to see output here.
Isolated sandbox · not executed on your devicePowered by Judge0 CE (free, self-hosted). Runs in an isolated sandbox — not on your device.
Editor
classListNode:
def__init__(self, val=0):
self.val = val
self.next = Nonedefbuild_list(values):
ifnot values:
returnNone
head = ListNode(values[0])
curr = head
for v in values[1:]:
curr.next = ListNode(v)
curr = curr.nextreturn head
values = list(map(int, input().split()))
head = build_list(values)
# TODO: iterative reversal — save next BEFORE overwriting current.next
prev, curr = None, head
Input (stdin)
Output
Run your code to see output here.
Isolated sandbox · not executed on your devicePowered by Judge0 CE (free, self-hosted). Runs in an isolated sandbox — not on your device.