NOTE

分隔链表

分隔链表的 LeetCode 解题笔记。

Data Structures & Algorithms创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 题目描述

给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你应当 保留 两个分区中每个节点的初始相对位置。

2. 思路

类似于快排的拆分

3. 实现

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func partition(head *ListNode, x int) *ListNode {
    leftDummyHead := &ListNode{}
    rightDummyHead := &ListNode{}
    l := leftDummyHead
    r := rightDummyHead

    current := head
    for current != nil {
        next := current.Next
        current.Next = nil
        if current.Val < x {
            l.Next = current
            l = l.Next
        } else {
            r.Next = current
            r = r.Next
        }
        current = next
    }

    l.Next = rightDummyHead.Next
    return leftDummyHead.Next
}

4. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看