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
相关推荐
kupeThinkPoem6 分钟前
哈希表有哪些算法?
数据结构·算法
小白程序员成长日记28 分钟前
2025.11.16 力扣每日一题
算法
Kuo-Teng1 小时前
LeetCode 118: Pascal‘s Triangle
java·算法·leetcode·职场和发展·动态规划
Greedy Alg1 小时前
LeetCode 32. 最长有效括号(困难)
算法
ShineWinsu2 小时前
对于数据结构:链式二叉树的超详细保姆级解析—中
数据结构·c++·算法·面试·二叉树·校招·递归
野蛮人6号2 小时前
力扣热题100道之207课程表
算法·leetcode·职场和发展
学学学无无止境2 小时前
力扣-买卖股票的最佳时机
leetcode
这周也會开心2 小时前
Map的遍历方式
数据结构·算法
无敌最俊朗@2 小时前
C++ 值类别与对象模型面试题(12)
算法
代码不停3 小时前
Java模拟算法题目练习
java·开发语言·算法