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
相关推荐
檐下翻书17315 分钟前
从入门到精通:流程图制作学习路径规划
论文阅读·人工智能·学习·算法·流程图·论文笔记
CoderYanger27 分钟前
B.双指针——3194. 最小元素和最大元素的最小平均值
java·开发语言·数据结构·算法·leetcode·职场和发展·1024程序员节
小曹要微笑2 小时前
STM32各系列时钟树详解
c语言·stm32·单片机·嵌入式硬件·算法
前进的李工3 小时前
LeetCode hot100:094 二叉树的中序遍历:从递归到迭代的完整指南
python·算法·leetcode·链表·二叉树
麦麦大数据3 小时前
F049 知识图谱双算法推荐在线学习系统vue+flask+neo4j之BS架构开题论文全源码
学习·算法·知识图谱·推荐算法·开题报告·学习系统·计算机毕业设计展示
兩尛4 小时前
215. 数组中的第K个最大元素
数据结构·算法·排序算法
952364 小时前
数据结构-堆
java·数据结构·学习·算法
吃着火锅x唱着歌4 小时前
LeetCode 面试题 16.24.数对和
算法·leetcode·职场和发展
不会编程的小寒4 小时前
数据结构 2.0
数据结构·算法
专注VB编程开发20年4 小时前
图片转矢量图(提取轮廓线条)Potrace:一个基于多边形的位图轮廓矢量化算法(translation)
算法·图片转矢量