天天看點

利用 python 完成 leetcode86 分隔連結清單

給定一個連結清單和一個特定值 x,對連結清單進行分隔,使得所有小于 x 的節點都在大于或等于 x 的節點之前。

你應當保留兩個分區中每個節點的初始相對位置。

示例:

輸入: head = 1->4->3->2->5->2, x = 3

輸出: 1->2->2->4->3->5

思路

将原連結清單中比x大的元素挪到另一個新連結清單中,最後将兩個連結清單首尾相連

代碼

def partition(self, head, x):
        if head==None or head.next==None:return head

        N=ListNode(0)
        N_head=N
        N.next=head
        T=ListNode(0)
        T_head=T
        
        while( N!=None and  N.next!=None):

            if N.next.val>=x:
                T.next=N.next
                N.next=N.next.next
                T=T.next
                T.next=None#将比x大的元素挪到另一個連結清單末尾
            else:
                N=N.next
        N.next=T_head.next#兩個連結清單相連
        
        return N_head.next