很好的一个模板题,链表找中点(快慢指针)和merge。
/**
* 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;
}
ListNode *prev = NULL;
ListNode *slow = head;
ListNode *fast = head;
while (fast != NULL && fast->next != NULL) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = NULL;
ListNode *l1 = sortList(head);
ListNode *l2 = sortList(slow);
return merge(l1, l2);
}
ListNode* merge(ListNode *l1, ListNode *l2) {
if (l1 == NULL ) {
return l2;
}
if (l2 == NULL) {
return l1;
}
if (l1->val <= l2->val) {
l1->next = merge(l1->next, l2);
return l1;
}
else {
l2->next = merge(l1, l2->next);