# Definition for singly-linked list.classListNode(object):def__init__(self,x):self.val=xself.next=NoneclassSolution(object):defpartition(self,head,x):""" :type head: ListNode :type x: int :rtype: ListNode """small=ListNode(0)small2=smalllarge=ListNode(0)large2=largewhilehead!=None:# create small and largesmall2.next=ListNode(head.val)small2=small2.nextlarge2.next=ListNode(head.val)large2=large2.nexthead=head.nextcurrent=small.nextprevious=smallwhilecurrent!=None:ifcurrent.val>=x:# delete val greater than or equal to xprevious.next=current.nextcurrent=previous.nextelse:# move onprevious=currentcurrent=current.nextcurrent2=large.nextprevious2=largewhilecurrent2!=None:ifcurrent2.val<x:# delete val smaller than xprevious2.next=current2.nextcurrent2=previous2.nextelse:# move onprevious2=current2current2=current2.next# concatenate small and largeprevious.next=large.nextreturnsmall.nextif__name__=="__main__":lst=ListNode(1)lst.next=ListNode(2)s=Solution()x=s.partition(lst,2)whilex!=None:printx.valx=x.next
近期评论