Reverse Linked List: the idea to remember.
Reverse a singly linked list and return its new head.
The core insight
Maintain a reversed prefix and an untouched suffix. Save the next node before redirecting the current pointer.
Why it works
After each iteration the previous pointer heads the correctly reversed visited prefix, while current still heads the unvisited suffix.
The mistake to avoid
Changing current.next before saving the original successor loses the rest of the list.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
ListNode reverseList(ListNode head) {
ListNode previous = null, current = head;
while (current != null) {
ListNode next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.