# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
dummy_head=ListNode(-1)
dummy_head.next=head
sorted_list=head
cur=head.next
while cur:
if sorted_list.val<=cur.val:
sorted_list=sorted_list.next
else:
pre=dummy_head
while pre.next.val<cur.val:
pre=pre.next
sorted_list.next=cur.next
cur.next=pre.next
pre.next=cur
cur=sorted_list.next
return dummy_head.next
LEETCODE 147. 对链表进行插入排序
最新推荐文章于 2024-07-20 22:34:59 发布