思路:新建两个空节点(为了边界条件的方便),分别记录小于 x 的子链、大于等于 x 的子链,最后连接起来,注意应该断掉的节点,否则会产生环。
code:
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
ListNode *p,*q, *t = head, *lessHead, *greaterHead;
p = new ListNode(0);
q = new ListNode(0);
lessHead = p;
greaterHead = q;
while(t != NULL){
if(t->val < x){
p->next = t;
p = p->next;
}
else{
q->next = t;
q = q->next;
}
t = t->next;
}
if(greaterHead->next == NULL || lessHead == NULL)
return head;
p->next = greaterHead->next;
q->next = NULL;
head = lessHead->next;
delete lessHead;
delete greaterHead;
return head;
}
};