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
相关推荐
沐苏瑶7 小时前
Java 搜索型数据结构全解:二叉搜索树、Map/Set 体系与哈希表
java·数据结构·算法
ZoeJoy88 小时前
算法筑基(二):搜索算法——从线性查找到图搜索,精准定位数据
算法·哈希算法·图搜索算法
Alicx.8 小时前
dfs由易到难
算法·蓝桥杯·宽度优先
_日拱一卒8 小时前
LeetCode:找到字符串中的所有字母异位词
算法·leetcode
云泽8089 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
Wilber的技术分享9 小时前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病10 小时前
Problem L. ZZUPC
c++·数学·算法·前缀和
梯度下降中11 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy11 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl2002092511 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划