给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
主要学习了评论区和B站上的代码
直接排序的话问题耗时过大
因此使用快指针和慢指针把链表切成两条
先把两个链表排序
然后再逐一对比两个链表的内容
连接在一起
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not (head and head.next): return head
slow,fast = head,head.next
while(fast and fast.next):
slow = slow.next
fast = fast.next.next
list2 = slow.next
slow.next = None
l,r = self.sortList(head),self.sortList(list2)
start = temp = ListNode(0)
while(l and r):
if l.val < r.val:
temp.next = l
l = l.next
else:
temp.next = r
r = r.next
temp = temp.next
temp.next = l if l else r
return start.next
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
Blibili:https://www.bilibili.com/video/BV1FV411k7MQ?from=search&seid=6746857253465802659&spm_id_from=333.337.0.0