首页 > 代码库 > 【Leetcode】Sort List
【Leetcode】Sort List
Sort a linked list in O(n log n) time using constant space complexity.
单向链表排序O(nlogn),Mergesort可以实现。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *sortList(ListNode *head) { 12 if (head == nullptr || head->next == nullptr) { 13 return head; 14 } 15 //快慢指针找中间节点 16 ListNode *fast = head, *slow = head; 17 while (fast->next != nullptr && fast->next->next != nullptr) { 18 fast = fast->next->next; 19 slow = slow->next; 20 } 21 22 fast = slow->next; 23 slow->next = nullptr; 24 ListNode *l1 = sortList(head); 25 ListNode *l2 = sortList(fast); 26 return mergeTwoLists(l1, l2); 27 } 28 29 private: 30 // Merge Two Sorted Lists 31 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 32 ListNode dummy(-1); 33 for (ListNode* p = &dummy; l1 != nullptr || l2 != nullptr; p = p->next) { 34 int val1 = l1 == nullptr ? INT_MAX : l1->val; 35 int val2 = l2 == nullptr ? INT_MAX : l2->val; 36 if (val1 <= val2) { 37 p->next = l1; 38 l1 = l1->next; 39 } else { 40 p->next = l2; 41 l2 = l2->next; 42 } 43 } 44 return dummy.next; 45 } 46 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。