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} head
10 * @param {number} x
11 * @return {ListNode}
12 */
13// not fair way
14var partition = function (head, x) {
15 const arr = []
16
17 while (head) {
18 arr.push(head.val)
19 head = head.next
20 }
21
22 const nodes = [...arr.filter(el => el < x), ...arr.filter(el => el >= x)].map(
23 el => new ListNode(el)
24 )
25
26 for (let i = 0; i < nodes.length - 1; i++) {
27 nodes[i].next = nodes[i + 1]
28 }
29
30 return nodes[0] || null
31}
32
33var 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 = head
39 } else {
40 dummy2 = dummy2.next = head
41 }
42 head = head.next
43 }
44 dummy2.next = null // avoid cyclic
45 dummy1.next = newHead2.next
46 newHead1 = newHead1.next
47 return newHead1
48}

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.

Next Post

LeetCode: Fibonacci Number

Apr 15, 2021

Previous Post

HoningJS

Search Posts