可以用对数组进行排序的方法对链表进行排序,但由于链表有单向访问的特点所以用归并排序比较合理。
ListNode *Merge(ListNode *pre1, ListNode *pre2){ ListNode *fir = pre1 -> next; ListNode *sec = pre2 -> next; ListNode *result = new ListNode(-1); ListNode *p = result; while(fir != nullptr && sec != nullptr){ if(fir -> val < sec -> val){ p -> next = fir; p = p -> next; fir = fir -> next; }else{ p -> next = sec; p = p -> next; sec = sec -> next; } } if(fir == nullptr){ while(sec != nullptr){ p -> next = sec; p = p -> next; sec = sec -> next; } p -> next = nullptr; } if(sec == nullptr){ while(fir != nullptr){ p -> next = fir; p = p -> next; fir = fir -> next; } p -> next = nullptr; } return result; } ListNode *MergeSort(ListNode *head, ListNode *tail){ if(head == tail){ ListNode *result = new ListNode(-1); result -> next = head; head -> next = nullptr; return result; } ListNode *mid = head; ListNode *fast = head; while(fast != tail && fast -> next != tail){ mid = mid -> next; fast = fast -> next -> next; } ListNode *tmp = mid -> next; ListNode *result1 = MergeSort(head, mid); ListNode *result2 = MergeSort(tmp, tail); return Merge(result1, result2); } ListNode *sortList(ListNode *head){ if(head == nullptr || head -> next == nullptr) return head; ListNode *tail = head; while(tail -> next != nullptr) tail = tail -> next; ListNode *result = MergeSort(head, tail); return result -> next; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/ny_mg/article/details/48129579