Skip to content

Instantly share code, notes, and snippets.

@maxgoren
Created April 9, 2023 18:52
Show Gist options
  • Save maxgoren/0ee643edcdba6c75313403d8846d284e to your computer and use it in GitHub Desktop.
Save maxgoren/0ee643edcdba6c75313403d8846d284e to your computer and use it in GitHub Desktop.
Partition a Linked list, pivoting around a value
ListNode* partition(ListNode* head, int x) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode l; ListNode *a = &l;
ListNode r; ListNode *b = &r;
ListNode* p = head;
while (p != nullptr) {
ListNode* t = p;
p = p->next;
t->next = nullptr;
if (t->val < x) {
a->next = t;
a = a->next;
} else {
b->next = t;
b = b->next;
}
}
a->next = r.next;
return l.next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment