【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
相关推荐
songx_9930 分钟前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
先做个垃圾出来………1 小时前
差分数组(Difference Array)
java·数据结构·算法
hansang_IR2 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
乐迪信息2 小时前
乐迪信息:AI摄像机在智慧煤矿人员安全与行为识别中的技术应用
大数据·人工智能·算法·安全·视觉检测
多恩Stone2 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
dragoooon343 小时前
[数据结构——lesson5.1链表的应用]
数据结构·链表
惯导马工3 小时前
【论文导读】IDOL: Inertial Deep Orientation-Estimation and Localization
深度学习·算法
老姜洛克3 小时前
自然语言处理(NLP)之n-gram从原理到实战
算法·nlp
1白天的黑夜14 小时前
哈希表-49.字母异位词分组-力扣(LeetCode)
c++·leetcode·哈希表
CoovallyAIHub4 小时前
基于YOLO集成模型的无人机多光谱风电部件缺陷检测
深度学习·算法·计算机视觉