sort-list——链表、快慢指针找中间、归并排序

本文介绍了一种使用快慢指针找到链表中点的方法,并通过递归地将链表分成两半,再进行归并排序的方式,在O(n log n)的时间复杂度内完成排序。该方法采用常数空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Sort a linked list in O(n log n) time using constant space complexity.

 

链表,快慢指针找中点,归并排序。

注意判断条件fast->next!=NULL&&fast->next->next!=NULL,若为fast!=NULL&&fast->next!=NULL则会出现内存溢出

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *sortList(ListNode *head) {
12         if(head==NULL || head->next==NULL)
13             return head;
14         ListNode* slow, *fast;
15         slow=head;
16         fast=head;
17         while(fast->next!=NULL&&fast->next->next!=NULL){
18             slow=slow->next;
19             fast=fast->next->next;
20         }
21         fast=slow;
22         slow=slow->next;
23         fast->next=NULL;
24         fast=sortList(head);
25         slow=sortList(slow);
26         return merge(fast,slow);
27         
28     }
29     ListNode *merge(ListNode *left, ListNode *right){
30         ListNode *res,*temp;
31         if(left==NULL){
32             res=right;
33             return res;
34         }
35         if(right==NULL){
36             res=left;
37             return res;
38         }
39         if(left->val<=right->val){
40             res=left;
41             left=left->next;
42         }else{
43             res=right;
44             right=right->next;
45         }
46         temp=res;
47         while(left!=NULL&&right!=NULL){
48             if(left->val<=right->val){
49                 temp->next=left;
50                 left=left->next;
51             }else{
52                 temp->next=right;
53                 right=right->next;
54             }
55             temp=temp->next;
56             
57         }
58         if(left!=NULL){
59             temp->next=left;
60         }
61         if(right!=NULL){
62             temp->next=right;
63         }
64         return res;
65     }
66 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值