https://leetcode.com/problems/sort-list/description/
Sort a linked list in O(n log n) time using constant space complexity.
链表类题目找中间点使用双指针算法,要判断head -> next != nullptr,一定要首先判断head != nullptr。
ListNode* findMid(ListNode* head){ ListNode* fast = head -> next; ListNode* slow = head; while(fast != nullptr && fast -> next != nullptr){ fast = fast -> next -> next; slow = slow -> next; } return slow; }
思考归并排序算法,
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* merge(ListNode* left,ListNode* right){ ListNode* dummy = new ListNode(-1); ListNode* p = dummy; while(left != nullptr && right != nullptr){ if(left -> val < right -> val){ dummy -> next = left; left = left -> next; dummy = dummy -> next; } else{ dummy -> next = right; right = right -> next; dummy = dummy -> next; } } if(left != nullptr){ dummy -> next = left; } if(right != nullptr){ dummy -> next = right; } return p -> next; } ListNode* findMid(ListNode* head){ ListNode* fast = head -> next; ListNode* slow = head; while(fast != nullptr && fast -> next != nullptr){ fast = fast -> next -> next; slow = slow -> next; } return slow; } ListNode* mergeSort(ListNode* head){ if(head == nullptr || head -> next == nullptr){ return head; } ListNode* midNode = findMid(head); ListNode* left = mergeSort(midNode -> next); midNode -> next = nullptr; ListNode* right = mergeSort(head); left = merge(left,right); return left; } ListNode* sortList(ListNode* head) { if(head == nullptr){ return head; } return mergeSort(head); } };