实现单链表排序 时间复杂度要求为 nlogn
由于是单链表,用快速排序无法往前面遍历(双向链表可以考虑),这里我们用到归并排序
代码如下:
/**
* 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 *onestep=head;
ListNode *twostep=head;//定义两个指针,一个走一步,一个走两步,用来找到中间节点
// ListNode *first=NULL;
// ListNode *second=NULL;
while(twostep->next!=NULL&&twostep->next->next!=NULL)
{
onestep=onestep->next;
twostep=twostep->next->next;
}
//此时onestep指向了整个链表的中间,如果偶数那么两边均衡,如果为奇数,指向正中间需要从onestep出分开
twostep=onestep;
onestep=onestep->next;//此时onestep指向后半部分
twostep->next=NULL;//将前半部分和后半部分分开
twostep=sortList(head);
onestep=sortList(onestep);
return meger(twostep,onestep);
}
ListNode *meger(ListNode *first,ListNode *second)
{
ListNode *result;
ListNode *p;
if(first==NULL)
return second;
if(second==NULL)
return first;
//初始化result
if(first->val
val){ result=first; first=first->next; } else { result=second; second=second->next; } p=result; while(first!=NULL&&second!=NULL) { if(first->val
val) { p->next=first; first=first->next; } else { p->next=second; second=second->next; } p=p->next; } if(first!=NULL) p->next=first; else if(second!=NULL) p->next=second; return result; } };