# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):defreverseBetween(self,head,m,n):""" :type head: ListNode :type m: int :type n: int :rtype: ListNode """ifm==n:returnheadcons=ListNode(0)cons.next=headcur=cons.nextpre=conscount=0# cursor to record the positionwhilecur!=None:count+=1ifcount==m:# delete node mtmp1=cur.valcur=cur.nextpre.next=curcontinueelifcount==n:# change the val of node ntmp2=cur.valcur.val=tmp1pre=curcur=cur.nextcur=cons.nextpre=conscount=0whilecur!=None:count+=1ifcount==m:# add new nodenewnode=ListNode(tmp2)pre.next=newnodenewnode.next=curbreakpre=curcur=cur.nextreturncons.next
近期评论