【C++】【LeetCode】148. Sort List

来源:互联网 发布:高达age知乎 编辑:程序博客网 时间:2024/06/09 20:57

题目

Sort a linked list in O(n log n) time using constant space complexity.

思路

可以使用归并排序,将链表分为前后两个链表,然后分别排序,进行归并。

代码

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* sortList(ListNode* head) {        if (head == NULL || head->next == NULL) {            return head;        }        ListNode* p1 = head;        ListNode* p2 = head;        ListNode* pre = head;        while (p2 != NULL && p2->next != NULL) {            pre = p1;            p1 = p1->next;            p2 = p2->next->next;        }        pre->next = NULL;        return merge(sortList(head), sortList(p1));    }    ListNode* merge(ListNode* l1, ListNode* l2) {        if (l1 == NULL) {            return l2;        }        if (l2 == NULL) {            return l1;        }        if (l1->val < l2->val) {            l1->next = merge(l1->next, l2);            return l1;        } else {            l2->next = merge(l1, l2->next);            return l2;        }    }};
原创粉丝点击