美文网首页
python实现leetcode之86. 分隔链表

python实现leetcode之86. 分隔链表

作者: 深圳都这么冷 | 来源:发表于2021-09-16 10:19 被阅读0次

解题思路

first_half尾插法保存小于x的元素
second_half尾插法保存大于等于x的元素
最后第一部分的尾部接第二部分的头部
保险起见,将第二部分的尾部设置为None
最后返回first_half头

亮点,使用ListNode(0)哨兵优化代码行

86. 分隔链表

代码

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

class Solution(object):
    def partition(self, head, x):
        first_half = first_tail = ListNode(0)
        second_half = second_tail = ListNode(0)
        while head:
            tmp = head.next
            if head.val < x:  # add to first_half
                first_tail.next = head
                first_tail = head
            else:  # add to second half
                second_tail.next = head
                second_tail = head
            head = tmp
        
        first_tail.next = second_half.next
        second_tail.next = None
        return first_half.next
效果图

相关文章

  • python实现leetcode之86. 分隔链表

    解题思路 first_half尾插法保存小于x的元素second_half尾插法保存大于等于x的元素最后第一部分的...

  • 86. 分隔链表

    86. 分隔链表[https://leetcode-cn.com/problems/partition-list/...

  • 86. 分隔链表

    86. 分隔链表[https://leetcode.cn/problems/partition-list/] 给你...

  • 力扣每日一题:86.分隔链表 创建大小链表与寻找第一个链表头两种

    86.分隔链表[https://leetcode-cn.com/problems/partition-list/s...

  • LeetCode 86. 分隔链表

    86. 分隔链表 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点...

  • leetcode 86. 分隔链表

    题目描述 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。你...

  • Leetcode归类

    链表: Leetcode-725:分隔链表

  • LeetCode 力扣 86. 分隔链表

    题目描述(中等难度) 题目描述的很难理解,其实回想一下快排就很好理解了。就是快排的分区,将链表分成了两部分,一部分...

  • 86. 分隔链表

    86. 分隔链表 问题 给定一个链表和一个特定值 ,对链表进行分隔,使得所有小于 的节点都在大于或等于的节点之前。...

  • 86. 分隔链表

    双指针法: 直觉我们可以用两个指针pbig 和 psmall 来追踪上述的两个链表。两个指针可以用于分别创建两个链...

网友评论

      本文标题:python实现leetcode之86. 分隔链表

      本文链接:https://www.haomeiwen.com/subject/kmslgltx.html