LeetCode-148.排序链表(Python)

题目链接

# 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]:
        dummy=ListNode()
        temp=[]
        if head is None:return head
        current=head
        while current:
            temp.append(current.val)
            current=current.next
        if len(temp)==1:
            return head
        temp.sort()
        current=dummy
        for node in temp:
            new_node=ListNode(node)
            current.next=new_node
            current=current.next
        return dummy.next

你可能感兴趣的:(leetcode,leetcode,链表,算法,python)