题目:
给你链表的头结点
head
,请将其按 升序 排列并返回 排序后的链表 。来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
示例:
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:输入:head = []
输出:[]
解法:
代码同力扣:147. 对链表进行插入排序(Python3)-CSDN博客。
代码:
# 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: Optional[ListNode]) -> Optional[ListNode]:nums = []while head:nums.append(head.val)head = head.nextnums.sort()head = point = ListNode(-5001)for num in nums:point.next = ListNode(num)point = point.nextreturn head.next