【LeetCode】86.分割链表

1. 题目

2. 分析

这题没有太大难度,主要是熟悉代码。

3. 代码

python 复制代码
# 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 = None
        lower_head_bak = None
        upper_head = None
        upper_head_bak = None
        
        if head is None:
            return None
        while(head):
            tmp = head.next
            if head.val < x:
                if lower_head:
                    lower_head.next = head
                else:
                    lower_head_bak = head
                lower_head = head # 更新结果
                lower_head.next = None
            else:
                if upper_head is None:
                    upper_head_bak = head
                else:
                    upper_head.next = head
                upper_head = head
                upper_head.next = None
            head = tmp
        if lower_head :
            lower_head.next = upper_head_bak
            return lower_head_bak
        elif lower_head is None and upper_head_bak:
            return upper_head_bak
相关推荐
girl-0726几秒前
2025.12.28代码分析总结
算法
NAGNIP3 小时前
GPT-5.1 发布:更聪明,也更有温度的 AI
人工智能·算法
NAGNIP3 小时前
激活函数有什么用?有哪些常用的激活函数?
人工智能·算法
元亓亓亓3 小时前
LeetCode热题100--416. 分割等和子集--中等
算法·leetcode·职场和发展
BanyeBirth3 小时前
C++差分数组(二维)
开发语言·c++·算法
xu_yule5 小时前
算法基础(数论)—算法基本定理
c++·算法·算数基本定理
CoderCodingNo6 小时前
【GESP】C++五级真题(结构体排序考点) luogu-B3968 [GESP202403 五级] 成绩排序
开发语言·c++·算法
YGGP7 小时前
【Golang】LeetCode 32. 最长有效括号
算法·leetcode
自然常数e7 小时前
字符函数和字符串函数
c语言·算法·visual studio