考虑左指针有右指针,开始时,直接将右指针移动到末尾,然后遍历左指针,遇到大于等于 x 的节点就移动到右指针的位置;
Python
# class ListNode:# def __init__(self, x):# self.val = x# self.next = None## 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可## # @param head ListNode类 # @param x int整型 # @return ListNode类#classSolution:defpartition(self,head: ListNode,x:int) -> ListNode:# write code here small = l =ListNode(0) large = r =ListNode(0) cur = headwhile cur:if cur.val < x: l.next = cur l = l.nextelse: r.next = cur r = r.next cur = cur.next l.next = large.next r.next =Nonereturn small.next