LeetCode: Sort List Solution
Yeah I skipped the follow-upApproach: my same ol' cheat
Convert the list into an array
Sort the array
Rebuild the array into a linked list
Implementation
1var sortList = function (head) {2 if (!head) return head34 let arr = []5 for (; head; head = head.next) {6 arr.push(head.val)7 }8 arr.sort((a, b) => a - b)910 arr = arr.map(val => new ListNode(val))11 for (let i = 0; i < arr.length - 1; i++) {12 arr[i].next = arr[i + 1]13 }1415 return arr[0]16}
References
Similar problems
Insertion Sort List
Sort Linked List Already Sorted Using Absolute Values
Comments
Loading comments...
Tags
leetcode
array
sorting
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: Longest Palindrome by Concatenating Two Letter Words
Things get messy sometimes
Previous Post
LeetCode: Add Strings
Add digits with carry