leetcode 147 对链表进行插入排序 C语言实现

题目

leetcode 147
leetcode 147 对链表进行插入排序 C语言实现_第1张图片
示例 1:

输入: 4->2->1->3
输出: 1->2->3->4
示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

代码
struct ListNode* insertionSortList(struct ListNode* head){
    if (head == NULL || head->next == NULL) return head;
    struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode));
    ret->next = head;
    struct ListNode *p = head->next, *pre, *q;
    head->next = NULL;
    //pre指针指向插入位置的前缀节点
    while (p != NULL) {
        pre = ret;
        while (pre->next != NULL && pre->next->val <= p->val) pre = pre->next;
        q = p;
        p = p->next;
        q->next = pre->next;
        pre->next = q;
    }
    return ret->next;
}

你可能感兴趣的:(LeetCode)