[Linked List]Sort List
otal Accepted: 59473 Total Submissions: 253637 Difficulty: Medium
Sort a linked list in O(n log n) time using constant space complexity.
递归版本,代码比较好理解,并不符合题目要求,题目要求常量的空间
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeSortList(ListNode* head1,ListNode* head2) { if(head1==NULL){ return head2; } if(head2==NULL){ return head1; } ListNode* newHead = head1->val < head2->val ? head1:head2; newHead->next = head1->val < head2->val ? mergeSortList(head1->next,head2):mergeSortList(head1,head2->next); return newHead; } int getListLength(ListNode *head) { int cnt = 0; while(head){ cnt++; head = head->next; } return cnt; } ListNode* sortList(ListNode* head) { int len = getListLength(head); if(len<=1){ return head; } int cnt = len/2; ListNode* p = head,*pre=NULL; while(cnt--){ pre = p; p = p->next; } ListNode* head2 = p; pre->next = NULL; ListNode* head1 = sortList(head); head2 = sortList(head2); return mergeSortList(head1,head2); } };
Next challenges: (M) Insertion Sort List
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记