leetcode_148 Sort List

来源:互联网 发布:淘宝一直等待揽件陷阱 编辑:程序博客网 时间:2024/06/05 09:35

题目分析:

  • 对链表进行排序,要求时间复杂度为O(nlogn),常量空间。

解题思路:

  • 归并排序实现

    基本思想:找到链表的中间节点,然后递归对前半部分和后半部分分别进行归并排序,然后将两个排好序的链表进行合并即可。

    注意:如果数组进行归并排序,则空间不为常量空间。

  • 实现程序

    //找链表的中间节点struct ListNode *getMidList(struct ListNode *head){    if (head == NULL || head->next == NULL)        return head;    struct ListNode *p = head;    struct ListNode *q = head;    // 利用快慢指针查找中间节点     while (q != NULL && q->next != NULL && q->next->next != NULL)    {        p = p->next;        q = q->next;        q = q->next;    }    return p;}//两个链表的合并操作struct ListNode *mergeList(struct ListNode *a, struct ListNode *b){    struct ListNode *head = (struct ListNode *) malloc (sizeof(struct ListNode));    struct ListNode *cur = head;    while (a != NULL && b != NULL)    {        if (a->val <= b->val)        {            cur->next = a;            a = a->next;        }        else        {            cur->next = b;            b = b->next;        }        cur = cur->next;    }    cur->next = a != NULL ? a : b;    return head->next;}// 对链表进行归并排序 struct ListNode *sortList(struct ListNode *head){    if (head == NULL || head->next == NULL)        return head;    // 获取中间及诶单     struct ListNode *mid = getMidList(head);     struct ListNode *next = mid->next;    mid->next = NULL;    // 对前半部分和后半部分递归进行归并排序     return mergeList(sortList(head), sortList(next));}
0 0