思路:把一个链表分成两个链表,小于x的为一个,大于等于x的为一个,分割完后将两链表进行连接;只是在链表的创建,以及最后首结点的返回需要多加判定条件,要注意一下;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *partition(ListNode *head, int x)
{
if (head == NULL)
{
return NULL;
}
//分成两个链表
ListNode *h1 = NULL, *h2 = NULL; //h1用于生成小于x的链表,h2用于生成大于等于x的链表
ListNode *h3 = NULL, *h4 = NULL; //h3指向小于x的链表的头节点,h4指向大于等于x的链表的头节点
bool flag1 = true, flag2 = true;
while (head)
{
if (head->val < x)
{
ListNode *temp = new ListNode(head->val);
if (flag1) //如果是首个结点,单独操作
{
h1 = temp;
h3 = h1;
flag1 = false;
}
else
{
h1->next = temp;
h1 = temp;
}
head = head->next;
}
else
{
ListNode *temp = new ListNode(head->val);
if (flag2) //如果是首个结点,单独操作
{
h2 = temp;
h4 = h2;
flag2 = false;
}
else
{
h2->next = temp;
h2 = temp;
}
head = head->next;
}
}
if (h1 == NULL) //如果小于x的链表为空,直接返回h4即可;
{
return h4;
}
else if (h2 == NULL) //如果大于等于x的链表为空,直接返回h3即可,不用连接两个链表;
{
return h3;
}
else
{
h1->next = h4;
h2->next = NULL;
return h3;
}
}