编写代码,以给定值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;
}
本文介绍了一种链表分割算法,该算法将链表中的结点根据给定值x进行分割,使得所有小于x的结点排在大于或等于x的结点之前。通过创建两个临时链表分别存储小于x和大于等于x的结点,最后将这两个链表连接起来,实现链表的有序分割。
274

被折叠的 条评论
为什么被折叠?



