Sort list by merge sort
使用归并排序对链表进行排序
O(nlgn) 的时间效率
/** * 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; //one node or none return head ListNode * fast = head; //to find the mid by using fast and slow pointer ListNode * slow = head; while (fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; slow = slow->next; } fast = slow->next; slow->next = NULL; ListNode * l1 = sortList (head); //merge sort in O(nlgn) ListNode * l2 = sortList (fast); return merge (l1, l2); } ListNode * merge (ListNode * l1, ListNode * l2) { ListNode * head = new ListNode (-1); ListNode * p = head; while (l1 != NULL && l2 != NULL) { if (l1->val < l2->val) { p->next = l1; l1 = l1->next; } else { p->next = l2; l2 = l2->next; } p = p->next; } p->next = (l1 == NULL) ? l2 : l1; return head->next; } };

浙公网安备 33010602011771号