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
相关推荐
YGGP4 分钟前
【Golang】LeetCode 2. 两数相加
开发语言·leetcode·golang
努力学算法的蒟蒻7 分钟前
day53(1.4)——leetcode面试经典150
算法·leetcode·面试
leiming69 分钟前
c++ transform算法
开发语言·c++·算法
橘颂TA21 分钟前
【剑斩OFFER】哈希表简介
数据结构·算法·散列表
小尧嵌入式22 分钟前
c++红黑树及B树B+树
开发语言·数据结构·c++·windows·b树·算法·排序算法
tobias.b28 分钟前
408真题解析-2009-10-数据结构-排序
数据结构·算法·排序算法·408考研·408真题·真题解析
Zachary_zlc31 分钟前
有向无环图检测算法和关键路径算法
算法
你撅嘴真丑33 分钟前
素数回文数的个数 与 求分数序列和
算法
Wuliwuliii41 分钟前
贡献延迟计算DP
数据结构·c++·算法·动态规划·dp
ysn111111 小时前
简单多边形三角剖分---耳切法(含源码)
算法