首页 > 代码库 > Leetcode:Sort List 对单链表归并排序
Leetcode:Sort List 对单链表归并排序
Sort a linked list in O(n log n) time using constant space complexity.
看到O(n log n)的排序算法,适合单链表的首先想到的就是归并排序
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode * findListMid(ListNode * head) { if(head == NULL)return NULL; ListNode * fast = head; ListNode * slow = head; while(fast->next) { if(fast->next->next) { fast = fast->next->next; slow = slow->next; } else return slow; } return slow; } ListNode * merge(ListNode * list1,ListNode * list2) { if(list1 == NULL)return list2; if(list2 == NULL)return list1; ListNode * head = NULL; if(list1->val >= list2->val) { head = list2; list2 = list2->next; } else if(list1->val < list2->val) { head = list1; list1 = list1->next; } ListNode * tail = head; while(list1 && list2) { if(list1->val >= list2->val) { tail->next = list2; tail = list2; list2 = list2->next; } else if(list1->val < list2->val) { tail->next = list1; tail = list1; list1 = list1->next; } } if(list1) tail->next = list1; if(list2) tail->next = list2; return head; } ListNode *sortList(ListNode *head) { if(head == NULL)return NULL; if(head->next == NULL)return head; ListNode * mid = findListMid(head); ListNode * m = mid->next; mid->next = NULL; ListNode * list1 = sortList(head); ListNode * list2 = sortList(m); ListNode * list = merge(list1,list2); return list; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。