解法与思路:
将小于某一值x的结点加到pless所指向的结点,将大于某一直x的结点加到pbigger所指向的结点。需要注意内存泄露与将pbigger最后一个结点next置为NULL。
/**
* 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 node1(0),node2(0);
ListNode *pless = &node1;
ListNode *pbigger = &node2;
while(head)
{
if(head->val < x)
{
pless->next = head;
pless = pless->next;
}
else
{
pbigger->next = head;
pbigger = pbigger->next;
}
head = head->next;
}
pbigger->next = NULL;
pless->next = node2.next;
return node1.next;
}
};