描述

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

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

Python

用before和after两个链表分别记录小于和不小于x的node,最后再连接起来即可

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        before = head_b =  ListNode(0)
        after = head_a = ListNode(0)
        while head:
            if head.val < x:
                before.next = head
                before = before.next
            else:
                after.next = head
                after = after.next
            head = head.next
            # if head.next: # head.next最后是空的时候的判断,但是head=head.next可以达到相同效果,没必要if
            #     head = head.next
            # else:
            #     break
        after.next = None 
        before.next = head_a.next # not linking 0 Node
        return head_b.next