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
相关推荐
有泽改之_33 分钟前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER38 分钟前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
t198751281 小时前
电力系统经典节点系统潮流计算MATLAB实现
人工智能·算法·matlab
断剑zou天涯1 小时前
【算法笔记】蓄水池算法
笔记·算法
长安er1 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢1 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
唯道行2 小时前
计算机图形学·23 Weiler-Athenton多边形裁剪算法
算法·计算机视觉·几何学·计算机图形学·opengl
CoderYanger2 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节
花月C2 小时前
个性化推荐:基于用户的协同过滤算法
开发语言·后端·算法·近邻算法
lxh01132 小时前
最长递增子序列
前端·数据结构·算法