单链表经典算法题之分割链表
给定一个头结点和一个值x,是链表中所有小于x的值都在x前面
typedef struct ListNode ListNode;
struct ListNode* partition(struct ListNode* head, int x) {
//思路一:在原链表上进行修改
//思路二:创建新链表,使用哨兵位,比x大的尾插,比x小的头插
//思路三:创建两个链表,一个是大链表,一个是小链表,都整一个哨兵位
if(head == NULL)
{
return head;
}
ListNode* lesshead = (ListNode*)malloc(sizeof(ListNode));
ListNode* greaterhead = (ListNode*)malloc(sizeof(ListNode));
ListNode* lesstail = lesshead;
ListNode* greatertail = greaterhead;
ListNode* pcur = head;
while(pcur)
{
if(pcur->val < x)
{
lesstail->next = pcur;
lesstail = lesstail->next;
}
else
{
greatertail->next = pcur;
greatertail = greatertail->next;
}
pcur = pcur->next;
}
//小链表的尾节点与大链表的第一个有效节点结合
greatertail->next = NULL;//防止死循环,并将next指针初始化
lesstail->next = greaterhead->next;
ListNode* ret = lesshead->next;
free(lesshead);
free(greaterhead);
lesshead = greaterhead = NULL;
return ret;
}
//超出时间限制只有一种情况:就是代码出现了死循环
//创建新链表时,若进行尾插,则要考虑