文章目录
  1. 1. Sort List
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

Sort List

题目

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

思路

归并排序

解题

c++ 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* 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 || !head->next)
return head;
ListNode* mid=getofMid(head);
ListNode* head1=mid->next;
mid->next=NULL;
return merge(sortList(head),sortList(head1));
}
ListNode* getofMid(ListNode* head){
ListNode *slow=head,*fast=head;
while(fast->next && fast->next->next){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
ListNode* merge(ListNode*l1,ListNode*l2){
ListNode dummy(-1);
ListNode *pre=&dummy;
while(l1 && l2){
if(l1->val<l2->val){
pre->next=l1;
l1=l1->next;
}
else{
pre->next=l2;
l2=l2->next;
}
pre=pre->next;
}
if(l1)
pre->next=l1;
if(l2)
pre->next=l2;
return dummy.next;
}
};

python 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if not head or not head.next:
return head
midd=self.getofMid(head)
next1=midd.next
midd.next=None
return self.merge(self.sortList(head),self.sortList(next1))

def getofMid(self,head):
slow=head
fast=head
while fast.next and fast.next.next:
slow=slow.next
fast=fast.next.next
return slow

def merge(self,head1,head2):
dummy=ListNode(-1)
pre=dummy
while head1 and head2:
if head1.val<head2.val:
pre.next=head1
head1=head1.next
else:
pre.next=head2
head2=head2.next
pre=pre.next
if head1:
pre.next=head1
if head2:
pre.next=head2
return dummy.next
文章目录
  1. 1. Sort List
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题