Problem:
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
Solutions:
C++:
void AddNode(ListNode*& head, ListNode*& tail, ListNode* elem)
{
if(head == NULL) {
head = elem;
tail = head;
} else {
tail->next = elem;
tail = tail->next;
}
}
ListNode *partition(ListNode *head, int x) {
if(head == NULL || head->next == NULL)
return head;
ListNode* lessList = NULL;
ListNode* lessList_cur = NULL;
ListNode* noLessList = NULL;
ListNode* noLessList_cur = NULL;
for(ListNode* cur = head; cur != NULL;) {
ListNode* temp = cur;
cur = cur->next;
temp->next = NULL;
if(temp->val < x)
AddNode(lessList, lessList_cur, temp);
else
AddNode(noLessList, noLessList_cur, temp);
}
if(lessList == NULL)
lessList = noLessList;
else
lessList_cur->next = noLessList;
return lessList;
}
Java
:
Python: