Leecode之分割链表

一.题目及剖析

https://leetcode.cn/problems/partition-list-lcci/description/

Leecode之分割链表_第1张图片

二.思路引入

就是将其分成大小两个链表,以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;
}

你可能感兴趣的:(链表,数据结构)