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
相关推荐
2401_8948281236 分钟前
从原理到实战:随机森林算法全解析(附 Python 完整代码)
开发语言·python·算法·随机森林
Remember_9931 小时前
【LeetCode精选算法】前缀和专题二
算法·哈希算法·散列表
源代码•宸1 小时前
Leetcode—509. 斐波那契数【简单】
经验分享·算法·leetcode·面试·golang·记忆化搜索·动规
博大世界2 小时前
matlab结构体数组定义
数据结构·算法
Loo国昌2 小时前
【LangChain1.0】第九阶段:文档处理工程 (LlamaIndex)
人工智能·后端·python·算法·langchain
Zach_yuan2 小时前
面向对象封装线程:用 C++ 封装 pthread
开发语言·c++·算法
踩坑记录3 小时前
leetcode hot100 206.反转链表 easy
leetcode
安特尼3 小时前
X 推荐算法分析
算法·机器学习·推荐算法
罗湖老棍子4 小时前
强迫症冒险家的任务清单:字典序最小拓扑排序
数据结构·算法·图论·拓扑排序
不穿格子的程序员4 小时前
从零开始写算法——回溯篇4:分割回文串 + N皇后
算法·深度优先·dfs