执行结果:通过
执行用时 :392 ms, 在所有 Python3 提交中击败了64.92%的用户
内存消耗 :15.7 MB, 在所有 Python3 提交中击败了7.38%的用户
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if head==None or head.next==None:
return head
p=head
while p.next!=None:
if p.val<=p.next.val: #如果已满足顺序,则跳到下一个节点
p=p.next
continue
tmp=p.next #将需要排序的的节点取出,并断开原有连接
p.next=p.next.next
tmp.next=None
if head.val>=tmp.val: #处理头节点的特殊情况
tmp.next=head
head=tmp
continue
t=head
while t != p:
if t.next.val<tmp.val:
t=t.next
else:
tmp.next=t.next
t.next=tmp
break
return head