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
相关推荐
YuTaoShao几秒前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
Wendy14418 小时前
【线性回归(最小二乘法MSE)】——机器学习
算法·机器学习·线性回归
拾光拾趣录8 小时前
括号生成算法
前端·算法
渣呵9 小时前
求不重叠区间总和最大值
算法
拾光拾趣录9 小时前
链表合并:双指针与递归
前端·javascript·算法
好易学·数据结构9 小时前
可视化图解算法56:岛屿数量
数据结构·算法·leetcode·力扣·回溯·牛客网
香蕉可乐荷包蛋10 小时前
AI算法之图像识别与分类
人工智能·学习·算法
chuxinweihui10 小时前
stack,queue,priority_queue的模拟实现及常用接口
算法
tomato0910 小时前
河南萌新联赛2025第(一)场:河南工业大学(补题)
c++·算法
墨染点香11 小时前
LeetCode Hot100【5. 最长回文子串】
算法·leetcode·职场和发展