1. 原始题目
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3 输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0 输出: -1->0->3->4->5
2. 思路
归并排序。这道题两个递归解决。非常简洁。快慢指针+归并排序。
3. 解题
1 class Solution: 2 def sortList(self, head: ListNode) -> ListNode: 3 if not head or not head.next:return head 4 p,q = head, head.next 5 while(q and q.next): # 快慢指针,p最终指向中点 6 p = p.next 7 q = q.next.next 8 head2 = p.next 9 p.next = None 10 head = self.sortList(head) # 排好序的左链表 11 head2 = self.sortList(head2) # 排好序的右链表 12 head = self.merge(head,head2) # 合并两个排好序的链表 13 return head 14 15 def merge(self,head1,head2): # 递归merge两个排好序的链表 16 if not head1:return head2 17 if not head2:return head1 18 if head1.val<head2.val: 19 next = head1.next 20 head1.next = self.merge(next,head2) 21 return head1 22 else: 23 next = head2.next 24 head2.next = self.merge(next,head1) 25 return head2
leetcode上有说可以将结点的所有数都保存下来再排序。排好序后再放到链表节点中。这种做法快,但并未实质性地交换结点。也可作为一种备选。
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 def sortList(self, head: 'ListNode') -> 'ListNode': 9 x=[]; 10 temp=head; 11 while(head != None): 12 x.append(head.val); 13 head=head.next; 14 x.sort(); 15 head =temp; 16 for i in x: 17 temp.val=i; 18 temp=temp.next; 19 return head;
来源:https://www.cnblogs.com/king-lps/p/10848182.html