zoukankan      html  css  js  c++  java
  • LeetCode 86. 分隔链表

    86. 分隔链表

    Difficulty: 中等

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

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

    示例:

    输入: head = 1->4->3->2->5->2, x = 3
    输出: 1->2->2->4->3->5
    

    Solution

    如果没有second.next = None这一行代码,新得出的链表中将会有一个环,比如根据下面给出的解法,first是1->2->2,second是4->3->5,此时second中的5节点仍然还是指向2(也就是first中的最后一个节点),然后first.next = high.next,此时链表中就存在一个环了。所以需要使得second链表的最后一个节点指向None。

    # 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:
            if not head: return None
            
            low, high = ListNode(-1), ListNode(-1)
            first, second = low, high
            
            while head:
                if head.val < x:
                    first.next = head
                    first = first.next
                else:
                    second.next = head
                    second = second.next
                head = head.next
            second.next = None
            first.next = high.next
            return low.next
    
  • 相关阅读:
    [微软认证]MCP问题解答
    邮件服务
    QueryString 整站过滤
    今天开始安卓的底层开发吧。
    所谓的回调函数
    UTF8 to unicode
    TCP/IP中的拥塞窗口控制机制
    (转)前端页面,页内锚定位分析
    远程连接Sql Server 2008 R2 命名实例
    字符编码研究
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14165016.html
Copyright © 2011-2022 走看看