分隔链表(LeetCode)

发布于:2024-07-31 ⋅ 阅读:(111) ⋅ 点赞:(0)

题目

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

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

示例1:

        输入:head =[1,4,3,2,5,2]x=2

        输出:[1,2,2,4,3,5]

 

示例2:

        输入:head=[2,1] ,x=2

        输出:[1,2]

提示:

  •   链表中节点的数目在范围[0,200]
  • -100<=Node.val<=100
  • -200<=x<=200

解题

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def partition(head: ListNode, x: int) -> ListNode:
    # 创建两个虚拟头节点
    smaller_head = ListNode(0)
    greater_head = ListNode(0)

    # 用两个指针来操作这两个链表
    smaller = smaller_head
    greater = greater_head

    # 遍历原链表
    while head:
        next_node = head.next  # 先保存下一个节点
        if head.val < x:
            # 如果节点值小于 x,将其加入到小链表
            smaller.next = head
            smaller = smaller.next
        else:
            # 否则加入到大链表
            greater.next = head
            greater = greater.next

        head.next = None  # 断开当前节点的 next 指针
        head = next_node  # 移动到下一个节点

    # 将大链表的末尾指向 None
    greater.next = None
    # 将小链表的末尾连接到大链表的头部
    smaller.next = greater_head.next

    return smaller_head.next


def create_linked_list(values):
    # 通过值列表创建链表
    if not values:
        return None
    head = ListNode(values[0])
    current = head
    for value in values[1:]:
        current.next = ListNode(value)
        current = current.next
    return head


def print_linked_list(head: ListNode):
    # 打印链表的值
    values = []
    while head:
        values.append(head.val)
        head = head.next
    print(" -> ".join(map(str, values)))


if __name__ == '__main__':
    test_values = [-1, 1, 2, 2, 4, 3, 5]
    test_x = 3
    # 创建链表
    test_head = create_linked_list(test_values)

    # 分隔链表
    new_head = partition(test_head, test_x)

    # 打印结果
    print("分隔后的链表:")
    print_linked_list(new_head)

分隔后的链表:
-1 -> 1 -> 2 -> 2 -> 4 -> 3 -> 5