LeetCode: Reverse Linked List Solution
Update head each iterationApproach
Update head until the initial head is tail
- Stay with the initial head
- Update new head as the initial head's next
- Each new updated head's next is the previous head
1Input: 1 (initial head) -> 2 -> 3 -> 423After iteration 1: 2 -> (1) -> 3 -> 44After iteration 2: 3 -> 2 -> (1) -> 456Output: 4 -> 3 -> 2 -> (1)
Implementation (iterative)
1var reverseList = function (head) {2 const curr = head34 while (curr && curr.next) {5 let next = curr.next67 curr.next = curr.next.next8 next.next = head910 head = next11 }1213 return head14}
Implementation (recursive)
1var reverseList = function (head) {2 if (!head || !head.next) return head3 const newHead = reverseList(head.next)4 head.next.next = head5 head.next = null6 return newHead7}
Comments
Loading comments...
Tags
leetcode
linked list
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Remove Linked List Elements
Keep next next
Previous Post
LeetCode: Linked List Cycle II
Same as LC 141, but different in return