链表的归并排序,废话不多说,需要注意的地方已经进行了注释,代码如下:
/**
* 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 *fast;
ListNode *slow;
fast = head;
slow = head;
while ( fast->next != NULL && fast->next->next != NULL )
{
fast = fast->next->next;
slow = slow->next;
}
if ( slow->next != NULL )
{
fast = slow->next;
slow->next = NULL;
slow = head;
}
return mergeList( sortList(slow), sortList(fast) );
}
private:
ListNode* mergeList( ListNode* a, ListNode* b )
{
//一个临时的头节点
ListNode *temp = new ListNode(0);
ListNode *current;
current = temp;
while ( a != NULL && b != NULL )
{
if ( a->val <= b->val )
{
current->next = a;
a = a->next;
current = current->next;
}
else
{
current->next = b;
b = b->next;
current = current->next;
}
}
//把剩下的非空链表继续接到头几点所在的链表
if ( a != NULL )
{
current->next = a;
}
if ( b != NULL )
{
current->next = b;
}
current = temp->next;
delete temp;
return current;
}
};