【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
相关推荐
浮沉9871 天前
二分查找算法概述&通用模板
算法
Keven_111 天前
算法札记:SPFA判负环算法的证明
算法
什巳1 天前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
Jerry1 天前
LeetCode 347. 前 K 个高频元素
算法
Young Doro1 天前
SAC 算法
线性代数·算法·机器学习
罗超驿1 天前
2.算法效率的核心密码:时间复杂度和空间复杂度详解
java·数据结构·算法
:-)1 天前
算法-堆排序
数据结构·算法·排序算法
星马梦缘1 天前
算法设计 期末复习笔记
算法·动态规划·二分图·最小生成树·线性规划·最大流