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
相关推荐
敲代码的瓦龙35 分钟前
西邮移动应用开发实验室2025年二面题解
开发语言·c++·算法
RTC老炮43 分钟前
webrtc弱网-RembThrottler类源码分析及算法原理
网络·算法·webrtc
野蛮人6号1 小时前
力扣热题100道之73矩阵置零
算法·leetcode·矩阵
野蛮人6号1 小时前
力扣热题100道之238除自身以外数组的乘积
算法·leetcode·职场和发展
坚持编程的菜鸟1 小时前
LeetCode每日一题——缀点成线
c语言·算法·leetcode
小梁努力敲代码1 小时前
java数据结构--LinkedList与链表
java·数据结构·链表
派大星爱吃猫1 小时前
直接插入排序详解
算法·排序算法·直接插入排序
qq_433554541 小时前
C++ 双向循环链表
开发语言·c++·链表
一只侯子2 小时前
Tuning——CC调试(适用高通)
开发语言·图像处理·笔记·学习·算法
csdn_aspnet2 小时前
直圆锥(Right Circular Cone)
算法·圆锥