要注意循环链表的情况,如果big在前,small在后的话,当smalltail 指向bighead的时候就有可能出现循环链表的情况。
所以这个时候,我们每次再做完了head = head->next 时候,if(big)这个时候要让big ->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 *smallhead = NULL;
ListNode *bighead = NULL;
ListNode *small = smallhead;
ListNode *big = bighead;
while(head)
{
if(head->val < x)
if(smallhead == NULL)
{
smallhead = head;
small = head;
}
else{
small->next = head;
small = small->next;
}
if(head->val >= x)
{
if(bighead == NULL)
{
bighead = head;
big = head;
}
else
{
big->next= head;
big = big->next;
}
}
head = head->next;
if(big)
big->next = NULL;
}
if(smallhead == NULL)
return bighead;
if(bighead == NULL)
return smallhead;
small->next = bighead;
return smallhead;
}
};