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
相关推荐
玛卡巴卡ldf几秒前
【LeetCode 手撕算法】(回溯)全排列DFS、子集、电话号码字母组合 九键、组合总和、括号生成、单词搜索、分割回文数
java·算法·leetcode·力扣
风筝在晴天搁浅4 分钟前
快手/腾讯 CodeTop LeetCode 43.字符串相乘
算法·leetcode
_深海凉_18 分钟前
LeetCode热题100-括号生成
算法·leetcode·职场和发展
Eloudy22 分钟前
表面码中的CNOT 门的共轭变换规则
算法·量子计算
人道领域1 小时前
【LeetCode刷题日记】二叉树翻转:递归与迭代全解析
java·算法·leetcode
AI科技星1 小时前
全域数学信息原本72分册(数学物理卷)
人工智能·算法·数学建模·数据挖掘·量子计算
进击的荆棘1 小时前
递归、搜索与回溯——综合(上)
c++·算法·leetcode·深度优先·dfs
平凡但不平庸的码农9 小时前
Go Slice 详解
算法·golang
炸膛坦客12 小时前
嵌入式 - 数据结构与算法:(1-7)数据结构 - 顺序表和链表的对比
数据结构·链表
Jasmine_llq12 小时前
《B3867 [GESP202309 三级] 小杨的储蓄》
算法·循环遍历·数组累加(模拟)·索引定位·顺序输出