python-leetcode-分隔链表

86. 分隔链表 - 力扣(LeetCode)

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]:
        # 创建两个虚拟头节点
        smaller_head = ListNode(0)
        greater_head = ListNode(0)
        
        # 初始化两个指针
        smaller = smaller_head
        greater = greater_head
        
        # 遍历链表
        while head:
            if head.val < x:
                # 将节点加入到小于 x 的链表中
                smaller.next = head
                smaller = smaller.next
            else:
                # 将节点加入到大于等于 x 的链表中
                greater.next = head
                greater = greater.next
            head = head.next
        
        # 断开大于等于 x 链表的末尾
        greater.next = None
        
        # 连接两个链表
        smaller.next = greater_head.next
        
        return smaller_head.next
相关推荐
Controller-Inversion1 分钟前
76. 最小覆盖子串
java·算法·leetcode
_日拱一卒4 分钟前
LeetCode:437路径总和Ⅲ
算法·leetcode·职场和发展
♡すぎ♡20 分钟前
ShaderLab:PBR+IBL(ShaderToy Translation)
算法·计算机图形学·着色器·pbr·ibl
Shadow(⊙o⊙)22 分钟前
前缀和:和可被K整除的子数组(normal)
数据结构·c++·算法
世纪末的小黑26 分钟前
【LeetCode自用】LeetCode自用记录贴,题目一:两数之和
数据结构·算法·leetcode
兰令水27 分钟前
topcode【随机算法题】【2026.5.22打卡-java版本】
java·算法·leetcode
Brilliantwxx36 分钟前
【C++】 认识STL set与map(基础接口+题目OJ运用)
开发语言·数据结构·c++·笔记·算法
05候补工程师38 分钟前
【线性代数】核心考点复习笔记:二次型配方法、施密特正交化步骤与特征值经典题型详解
经验分享·笔记·线性代数·考研·算法
Deep-w41 分钟前
【MATLAB】基于遗传算法的直流电机 PI 控制器参数优化研究
开发语言·算法·matlab
暴力求解1 小时前
数据结构---二叉树及堆的实现
数据结构·算法·二叉树