struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode* p = head;
ListNode* smallerNow = NULL;
ListNode* smallerHead = NULL;
ListNode* greaterNow = NULL;
ListNode* greaterHead = NULL;
while (p)
{
if(p->val < x)
{
if(!smallerHead) smallerNow = smallerHead = p;
else smallerNow->next = p, smallerNow = p;
}
else
{
if(!greaterHead) greaterNow = greaterHead = p;
else greaterNow->next = p, greaterNow = p;
}
p = p->next;
}
if(greaterHead) greaterNow->next = NULL;
if(smallerHead) smallerNow->next = NULL;
if(!smallerHead && !greaterHead) return NULL;
else if(!smallerHead) return greaterHead;
else
{
smallerNow->next = greaterHead;
return smallerHead;
}
}
};
second time
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode dummy1(-1);
ListNode dummy2(-1);
ListNode* prev1 = &dummy1;
ListNode* prev2 = &dummy2;
ListNode* cur = head;
while(cur != NULL)
{
if(cur->val < x)
{
prev1->next = cur;
prev1 = prev1->next;
}
else
{
prev2->next = cur;
prev2 = prev2->next;
}
cur = cur->next;
}
prev1->next = NULL;
prev2->next = NULL;
if(dummy1.next == NULL) return dummy2.next;
else
{
prev1->next = dummy2.next;
return dummy1.next;
}
}
};