问题描述
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param x int整型
* @return ListNode类
*/
struct ListNode* partition(struct ListNode* head, int x ) {
// write code here
struct ListNode* smallerhead = NULL, *smallertail = NULL;
struct ListNode* biggerhead = NULL, *biggertail = NULL;
struct ListNode* pt = head;
if(head==NULL){
return NULL;
}
while (pt) {
if (pt->val < x ) {
if (smallerhead == NULL) {
smallerhead =smallertail= pt;
}
else{
smallertail->next = pt;
smallertail=pt;
}
} else {
if (biggerhead == NULL) {
biggerhead=biggertail = pt;
}
else{
biggertail->next = pt;
biggertail=pt;
}
}
pt = pt->next;
}
if(smallertail){
smallertail->next=biggerhead;
return smallerhead;
}
else{
return biggerhead;
}
}
以上是原先的代码,提交后发现
这边死循环了,而且发现5 2 4 3 5重复出现
原因分析:
将原数据重新走一遍后,发现这个5还跟2链接着,所以最后输出时就会死循环,类似下图这样
解决方案:
所以这边想到了在最后把biggertail->next 给置空,这样就不会牵连到2了