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
相关推荐
NAGNIP4 小时前
轻松搞懂全连接神经网络结构!
人工智能·算法·面试
NAGNIP4 小时前
一文搞懂激活函数!
算法·面试
董董灿是个攻城狮4 小时前
AI 视觉连载7:传统 CV 之高斯滤波实战
算法
爱理财的程序媛10 小时前
openclaw 盯盘实践
算法
MobotStone14 小时前
Google发布Nano Banana 2:更快更便宜,图片生成能力全面升级
算法
颜酱17 小时前
队列练习系列:从基础到进阶的完整实现
javascript·后端·算法
用户57573033462417 小时前
两数之和:从 JSON 对象到 Map,大厂面试官到底在考察什么?
算法
程序猿追17 小时前
“马”上行动:手把手教你基于灵珠平台打造春节“全能数字管家”
算法
ZPC82101 天前
docker 镜像备份
人工智能·算法·fpga开发·机器人