0
点赞
收藏
分享

微信扫一扫

【面试题 02.04. 分割链表】

骑在牛背上看书 2022-02-06 阅读 50

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

你不需要 保留 每个分区中各节点的初始相对位置。

示例 1:


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

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

提示:

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

方法:新建两链表

遍历原有链表,小于x位sml链表,大于等于x位big链表,然后把sml的尾部和big的头部相连,返回sml头部,就是最终的结果

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        small_node,big_node=ListNode(0),ListNode(0)
        sml,big=small_node,big_node
        while head:
            if head.val<x:
                sml.next=head
                sml=sml.next
            else:
                big.next=head
                big=big.next
            head=head.next
        sml.next=big_node.next
        big.next=None
        return small_node.next
举报

相关推荐

0 条评论