Skip to main content

86. Partition List

https://leetcode.com/problems/partition-list/

Python

class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
front_head = ListNode()
after_head = ListNode()

front_cur, after_cur = front_head, after_head
cur = head

while cur:
if cur.val < x:
front_cur.next = cur
front_cur = front_cur.next
else:
after_cur.next = cur
after_cur = after_cur.next
cur = cur.next

after_cur.next = None
front_cur.next = after_head.next

return front_head.next

Javascript

var partition = function(head, x) {
let lessHeader = new ListNode();
let less = lessHeader;

let greaterHeader = new ListNode();
let greater = greaterHeader;

while (head !== null) {
if (head.val < x) {
less.next = head;
less = less.next;
} else {
greater.next = head;
greater = greater.next;
}

head = head.next;
}

greater.next = null;

less.next = greaterHeader.next;

return lessHeader.next;
};