天天看点

利用 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