LeetCode: Sort List Solution

Yeah I skipped the follow-up

Approach: 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 head
3
4 let arr = []
5 for (; head; head = head.next) {
6 arr.push(head.val)
7 }
8 arr.sort((a, b) => a - b)
9
10 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 }
14
15 return arr[0]
16}

References

Original problem

Similar problems

Merge Two Sorted Lists

Sort Colors

Insertion Sort List

Sort Linked List Already Sorted Using Absolute Values

Comments

Loading comments...

Tags

leetcode

array

sorting

linked list

Next Post

LeetCode: Longest Palindrome by Concatenating Two Letter Words

Things get messy sometimes

Previous Post

LeetCode: Add Strings

Add digits with carry

HoningJS

Search Posts