# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):definsertionSortList(self,head):""" :type head: ListNode :rtype: ListNode """ifnothead:returnNoneifnothead.next:returnheadcur=head.nextbeforecur=headwhilecur:tmp=headbeforetmp=Nonewhilecurandtmp.val<cur.val:# find the before node which is greater than curbeforetmp=tmptmp=tmp.nextiftmp==cur:# if no before node greater than cur, continuebeforecur=tmpcur=cur.nextcontinuetmpnode=ListNode(cur.val)# 3(tmp)-2(beforecur)-4(cur)tmpnode.next=tmpbeforecur.next=cur.nextifbeforetmp:beforetmp.next=tmpnodeelse:head=tmpnodecur=beforecur.next# cur already removed, set cur as beforecur.nextreturnhead
近期评论