题目:

思路:

借助list

  1. 新建list()
  2. 遍历链表,把数字加到list中
  3. 调用list的排序函数进行排序
  4. 把排序后的元素放到链表中
# 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]:
        new_list = list()
        curr = head
        while curr:
            new_list.append(curr.val)
            curr = curr.next
        new_list.sort()
        dump = ListNode(-1,head)
        temp = dump
        for num in new_list:
            new_node = ListNode(num)
            temp.next = new_node
            temp = temp.next
        return dump.next
        

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐