Reverse Linked List: Inverting Node Connections
The "Reverse Linked List" problem is a classic algorithmic challenge, involving the reversal of a singly linked list.
Problem Statement
Given the head of a singly linked list, reverse the list and return the reversed list.
Example
Consider a linked list: 1 -> 2 -> 3 -> 4 -> 5
After reversing, the list becomes: 5 -> 4 -> 3 -> 2 -> 1
Iterative Solution
Breaking Down the Solution
- Initialize Pointers: Start with
prevset tonullandcurrentset to the head of the list. - Iterate Through List: Traverse the list, reversing the pointers at each node.
- Update Pointers: For each node, point it to the
prevnode, then updateprevto be the current node and movecurrentto the next node in the original list. - Return New Head: At the end of the iteration,
prevwill be the new head of the reversed list.
Conclusion
The Reverse Linked List problem is a fundamental exercise in linked list manipulation, demonstrating the importance of pointer manipulation in data structures. It is a valuable skill for understanding more complex linked list operations and problems.
Rust Solution
The list is modelled as Option<Box<ListNode>> — an owned heap pointer that is either Some or None, so absence is a real variant instead of the null the JS version guards against. node.next.take() is what makes the in-place reversal legal: it moves the next value out and leaves None behind, sidestepping the borrow checker's refusal to read and reassign the same field at once. The while let Some(mut node) = head loop consumes the list one owned Box at a time rather than following a mutable pointer. vec_to_list rebuilds it back-to-front with v.iter().rev(), and list_to_vec walks it through a shared & borrow (cur = &node.next), so reading the values never takes ownership of the list.
Go Solution
reverseList mirrors the JS iterative version almost line for line, because Go's *ListNode pointer and its nil zero value behave like a null-terminated list — var prev *ListNode starts nil with no initialiser, and nextTemp := current.Next keeps the same explicit temporary. sliceToList leans on a dummy := &ListNode{} sentinel so appending to the tail needs no special case for the first node, then returns dummy.Next. The for _, x := range v loop discards the index via the blank identifier _, and listToSlice grows a nil var res []int with append — which would leave res as nil rather than an empty slice had the list been empty.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.