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
.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode firstnode1(-1);
ListNode firstnode2(-1);
ListNode* pre1 = &firstnode1;
ListNode* pre2 = &firstnode2;
ListNode* curr = head;
while (curr != nullptr)
{
if (curr->val < x)
{
pre1->next = curr;
pre1 = curr;
}
else
{
pre2->next = curr;
pre2 = curr;
}
curr = curr->next;
}
pre1->next = firstnode2.next;
pre2->next = nullptr;
return firstnode1.next;
}
};