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
相关推荐
高山上有一只小老虎1 小时前
字符串字符匹配
java·算法
愚润求学1 小时前
【动态规划】专题完结,题单汇总
算法·leetcode·动态规划
林太白1 小时前
跟着TRAE SOLO学习两大搜索
前端·算法
ghie90902 小时前
图像去雾算法详解与MATLAB实现
开发语言·算法·matlab
云泽8082 小时前
从三路快排到内省排序:探索工业级排序算法的演进
算法·排序算法
weixin_468466852 小时前
遗传算法求解TSP旅行商问题python代码实战
python·算法·算法优化·遗传算法·旅行商问题·智能优化·np问题
·白小白3 小时前
力扣(LeetCode) ——43.字符串相乘(C++)
c++·leetcode
FMRbpm3 小时前
链表5--------删除
数据结构·c++·算法·链表·新手入门
程序员buddha3 小时前
C语言操作符详解
java·c语言·算法
John_Rey3 小时前
API 设计哲学:构建健壮、易用且符合惯用语的 Rust 库
网络·算法·rust