1. 题目
2. 分析
这题没有太大难度,主要是熟悉代码。
3. 代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:lower_head = Nonelower_head_bak = Noneupper_head = Noneupper_head_bak = Noneif head is None:return Nonewhile(head):tmp = head.nextif head.val < x:if lower_head:lower_head.next = headelse:lower_head_bak = headlower_head = head # 更新结果lower_head.next = Noneelse:if upper_head is None:upper_head_bak = headelse:upper_head.next = headupper_head = headupper_head.next = Nonehead = tmpif lower_head :lower_head.next = upper_head_bakreturn lower_head_bakelif lower_head is None and upper_head_bak:return upper_head_bak