题目链接:
解题思路:
1. 要注意其与 x 的值进行比较后的这些数字的相对顺序不能改变,所以不能用 “ 逐步头插 ” 去解决
2. 思路:
新建俩个带哨兵位的链表,比 x 值大的数字通过 “ 尾插 ” 操作放在第一个链表中,比 x 值小的数字通过 “ 尾插 ” 操作放在第二个链表中
最后把这俩个链表连接起来,然后分别把头结点释放
尾插操作不会改变其数字间的相对顺序
3. 注意:
如果尾插到最后一个结点被放在其中一个链表中,而这个结点中的指针域没有被置为 NULL 那么此
时会形成环结构,造成使用用例出错。如下图:
参考代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
ListNode* partition(ListNode* pHead, int x)
{
struct ListNode *bighead,*bigtail,*smallhead,*smalltail;
smallhead = smalltail = (struct ListNode*)malloc(sizeof(struct ListNode));
bighead = bigtail = (struct ListNode*)malloc(sizeof(struct ListNode));
//bigtail = smalltail = NULL;
//对哨兵位里的指针域进行初始化
bigtail->next = NULL;
smalltail->next = NULL;
struct ListNode *cur = pHead;
while (cur)
{
if ((cur->val) < x)
{
smalltail->next = cur;
smalltail = smalltail->next;
}
else
{
bigtail->next = cur;
bigtail = bigtail->next;
}
cur = cur->next;
}
bigtail->next = NULL;
smalltail->next = bighead->next;
struct ListNode *list = smallhead->next;
free(smallhead);
free(bighead);
return list;
}
};