题目要求时间复杂度为O(nlogn),符合要求的排序算法有快速排序,归并排序,堆排序。
此出利用归并排序方法
代码
ListNode * mergeList(ListNode * fast, ListNode * slow)
{
if(fast == NULL) return slow;
if(slow == NULL) return fast;
ListNode * res, *p;
if(fast ->val < slow ->val)
{
res = fast;
fast = fast -> next;
}
else
{
res = slow;
slow = slow ->next;
}
//利用p来遍历,res记录合并后的头节点位置
p = res;
while(fast != NULL && slow != NULL)
{
if(fast ->val < slow ->val)
{
p->next = fast;
fast = fast -> next;
}
else
{
p ->next = slow;
slow = slow ->next;
}
p = p ->next;
}
if(fast != NULL)
p->next = fast;
else if(slow != NULL)
p ->next = slow;
return res;
}
ListNode *sortList(ListNode * head)
{
if(head == NULL || head ->next == NULL)
return head;
else
{
ListNode * slow , * fast;
slow = head;
fast = head;
while(fast ->next!= NULL && fast ->next ->next != NULL)
{
slow = slow ->next;
fast = fast ->next ->next;
}
fast = slow;
slow = slow ->next;
fast->next = NULL;
fast = sortList(head);
slow = sortList(slow);
return mergeList(fast, slow);
}
}
主要注意链表的创建
// 逆序创建链表
void creatList(ListNode *& head, int n)
{
ListNode *p;
int tempvalue;
head = (ListNode*)malloc(sizeof(ListNode));
head ->next = NULL;
for(int i = 0; i < n; ++i)
{
p = (ListNode*)malloc(sizeof(ListNode));
cin>>p->val;
p->next = head ->next;
head ->next = p;
}
}