一.题目及剖析
https://leetcode.cn/problems/partition-list-lcci/description/
二.思路引入
就是将其分成大小两个链表,以x为分界线进行分堆,最后再将两链表合并
三.代码引入
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x){
if(head == NULL)
return head;
struct ListNode *lessHead, *lessTail, *greaterHead, *greaterTail, *pcur;
lessHead = lessTail = (struct ListNode*)malloc(sizeof(struct ListNode));
greaterHead = greaterTail = (struct ListNode*)malloc(sizeof(struct 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;
lessTail->next = greaterHead->next;
return lessHead->next;
}