Description
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input:
4->2->1->3
Output:
1->2->3->4
Example 2:
Input:
-1->5->3->4->0
Output:
-1->0->3->4->5
分析
题目的意思是:常量空间复杂度排序好一个链表。
- 找到链表中点,(快慢指针的思路),写出merge函数归并两个链表。
C++
/**
* 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* p=head;
ListNode* q=head->next;
while(q&&q->next){
p=p->next;
q=q->next->next;
}
ListNode* left=sortList(p->next);
p->next=NULL;
ListNode* right=sortList(head);
return mergeList(left,right);
}
ListNode* mergeList(ListNode* left,ListNode* right){
ListNode* dummy = new ListNode(0);
ListNode *p=dummy;
while(left&&right){
if(left->val<right->val){
p->next=left;
left=left->next;
}else{
p->next=right;
right=right->next;
}
p=p->next;
}
if(left){
p->next=left;
}
if(right){
p->next=right;
}
return dummy->next;
}
};
Python
如果能想到归并排序+快慢指针,并了解其中的归并的写法就能做出来。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def merge_sort(self, left, right):
dummy = ListNode(-1)
p = dummy
while left and right:
if left.val<=right.val:
p.next = left
left = left.next
else:
p.next = right
right = right.next
p = p.next
if left:
p.next = left
if right:
p.next = right
return dummy.next
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# merge sort
if head is None or head.next is None:
return head
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
p = slow.next
slow.next = None
left = self.sortList(head)
right = self.sortList(p)
return self.merge_sort(left, right)