题目
对一个链表插入排序。
使用了简单的指针方法。
我的代码(效率太低没办法通过)
# 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 not head:
return head
pp=head
p=head.next
while p:
q=head
qp=None
while p!=q:
if p.val<q.val:
if qp==None:
head=p
else:
qp.next=p
pp.next=p.next
p.next=q
break
else:
qp=q
q=q.next
pp=p
p=p.next
return head
高效代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def insertionSortList(self, head):
p = dummy = ListNode(0)
cur = dummy.next = head
while cur and cur.next:
val = cur.next.val
if cur.val < val:
cur = cur.next
continue
if p.next.val > val:
p = dummy
while p.next.val < val:
p = p.next
new = cur.next
cur.next = new.next
new.next = p.next
p.next = new
return dummy.next
代入4213 大概画下图就能够理解了。