/**
* 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;
return recursiveSort(head);
}
ListNode* recursiveSort(ListNode* head)//归并过程
{
ListNode *fast, *slow;
fast=slow=head;
while(NULL!=fast->next&&NULL!=fast->next->next)//在找中点的时候使用到快慢指针的技巧
{
fast=fast->next->next;
slow=slow->next;
}
if(fast!=head)//如果可以继续递归
{
ListNode *part2=slow->next;
slow->next=NULL;
ListNode *first=recursiveSort(head);
ListNode *second=recursiveSort(part2);
return mergeListNode(first, second);
}
else//无法递归下去
{
ListNode *part2=head->next;
head->next=NULL;
return mergeListNode(head, part2);
}
}
ListNode* mergeListNode(ListNode* l1, ListNode* l2)//对两个链表进行排序
{
if(NULL==l1) return l2;
if(NULL==l2) return l1;
ListNode* dummy=new ListNode(-1), *cur=dummy;
while(NULL!=l1&&NULL!=l2)
{
if(l1->val<l2->val)
{
cur->next=l1;
l1=l1->next;
cur=cur->next;
}
else
{
cur->next=l2;
l2=l2->next;
cur=cur->next;
}
}
if(l1) cur->next=l1;
if(l2) cur->next=l2;
return dummy->next;
}
};
[LeetCode148]Sort List(对链表排序)
最新推荐文章于 2025-01-15 18:00:00 发布