【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
相关推荐
mmz12077 分钟前
双指针问题5(c++)
c++·算法
星空露珠9 分钟前
lua获取随机颜色rgb转换hex
数据结构·数据库·算法·游戏·lua
mit6.82414 分钟前
预hash|vector<int> dfs
算法
Zsy_05100316 分钟前
【数据结构】堆简单介绍、C语言实现堆和堆排序
c语言·数据结构·算法
Rock_yzh16 分钟前
LeetCode算法刷题——56. 合并区间
数据结构·c++·学习·算法·leetcode·职场和发展·动态规划
sheeta199821 分钟前
LeetCode 每日一题笔记 日期:2025.12.02 题目:3623. 统计梯形的数目 I
笔记·算法·leetcode
宇来风满楼21 分钟前
U-KAN复现
人工智能·深度学习·神经网络·算法·机器学习
W_chuanqi30 分钟前
单目标实数参数优化:算法jSO
算法
老鱼说AI37 分钟前
算法初级教学第三步:链表
数据结构·算法·链表