题目链接: Sort List
题目意思: 给定一个链表头结点,在O(nlogn)时间内进行排序
分析: 比较排序下限是O(nlogn),可以选择归并排序解决(事实证明,快速排序会TLE)
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void merge(vector<ListNode*> &arrList, int begin, int mid, int end); void mergeSort(vector<ListNode*> &arrList, int begin, int end); ListNode *sortList(ListNode *head); }; void Solution::merge(vector<ListNode*> &arrList, int begin, int mid, int end){ int i = begin; int j = mid+1; int pos = 0; int* tmpArr = new int[end-begin+2]; while ((i <= mid) && (j <= end)) { if (arrList[i]->val <= arrList[j]->val) { tmpArr[pos++] = arrList[i++]->val; } else { tmpArr[pos++] = arrList[j++]->val; } } while (i <= mid) { tmpArr[pos++] = arrList[i++]->val; } while (j <= end) { tmpArr[pos++] = arrList[j++]->val; } for (i = 0, j = begin; i < pos; i++, j++) { arrList[j]->val = tmpArr[i]; } delete tmpArr; tmpArr = NULL; } void Solution::mergeSort(vector<ListNode*> &arrList, int begin, int end) { if (begin >= end) { return; } int mid = (begin+end) >> 1; mergeSort(arrList, begin, mid); mergeSort(arrList, mid+1, end); merge(arrList, begin, mid, end); } ListNode* Solution::sortList(ListNode *head) { if (NULL == head) { return NULL; } ListNode* tmpHead = head; vector<ListNode*> arrList; while (tmpHead != NULL) { arrList.push_back(tmpHead); tmpHead = tmpHead->next; } mergeSort(arrList, 0, arrList.size()-1); return head; }