编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前 。
解题思路:
1.新建两个链表,一个存放所有小于x的结点,另一个存放所有大于x的结点。
2.把两个链表拼接,第一个链表的尾连接第二个链表的头。
3.返回第一个链表的有效结点。
ListNode* partition(ListNode* pHead, int x)
{
struct ListNode* lhead ,*ltail;
struct ListNode* ghead,*gtail;
struct ListNode* cur = pHead;
ltail = lhead = (struct ListNode*)malloc(sizeof(struct ListNode));
gtail = ghead = (struct ListNode*)malloc(sizeof(struct ListNode));
//遍历每一个元素
while(cur)
{
//判断当前元素是否小于x
if(cur->val < x)
{
ltail->next = cur;
ltail = ltail->next;
}
else
{
gtail->next = cur;
gtail = gtail->next;
}
cur = cur->next;
}
//连接两个新的链表
ltail->next = ghead->next;
//链表最后一个为NULL
gtail->next = NULL;
pHead = lhead->next;
free(lhead);
free(ghead);
return pHead;
}