Build two linked list to track small element and large element.
ListNode* partition(ListNode* head, int k){
if(!head ) return head;
ListNode* newHeadS = new ListNode(-1);
ListNode* newHeadL = new ListNode(-2);
ListNode* small = newHeadS;
ListNode* large = newHeadL;
while (head){
if (head->val < k){
small->next = head;
small = small->next;
}else {
large->next = head;
large = large->next;
}
head = head->next;
}
small->next = newHeadL->next;
large->next = NULL;
return newHeadS->next;
}
Testing:
void insert( ListNode * & head, int data ) {
ListNode * newNode = new ListNode(data);
if ( head == nullptr ) {
head = newNode;
} else {
ListNode * curr = head;
while( curr->next ) {
curr = curr->next;
}
curr->next = newNode;
}
}
int main(int argc, const char * argv[]) {
// insert code here...
ListNode * head = nullptr;
for ( int i = 0; i < 10; ++i ) {
insert(head, random_range(1,9));
}
cout << "List before partition around 5:\n";
printList(head);
ListNode* part = partition(head, 5);
cout << "List after partition around 5:\n";
printList(part);
return 0;
}