LeetCode: Partition List Solution
1/**2 * Definition for singly-linked list.3 * function ListNode(val, next) {4 * this.val = (val===undefined ? 0 : val)5 * this.next = (next===undefined ? null : next)6 * }7 */8/**9 * @param {ListNode} head10 * @param {number} x11 * @return {ListNode}12 */13// not fair way14var partition = function (head, x) {15 const arr = []1617 while (head) {18 arr.push(head.val)19 head = head.next20 }2122 const nodes = [...arr.filter(el => el < x), ...arr.filter(el => el >= x)].map(23 el => new ListNode(el)24 )2526 for (let i = 0; i < nodes.length - 1; i++) {27 nodes[i].next = nodes[i + 1]28 }2930 return nodes[0] || null31}3233var partition = function (head, x) {34 let [dummy1, dummy2] = [new ListNode(0), new ListNode(0)]35 let [newHead1, newHead2] = [dummy1, dummy2]36 while (head) {37 if (head.val < x) {38 dummy1 = dummy1.next = head39 } else {40 dummy2 = dummy2.next = head41 }42 head = head.next43 }44 dummy2.next = null // avoid cyclic45 dummy1.next = newHead2.next46 newHead1 = newHead1.next47 return newHead148}
Comments
Loading comments...
Tags
leetcode
linked list
two pointers
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.