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
    
  • 相关阅读:
    javaEE项目部署方式
    Docker安装mysql5.6
    自定义镜像mycentos
    DockerFile体系结构(保留字指令)
    Cognition math based on Factor Space (2016.05)
    MATLAB画ROC曲线,及计算AUC值
    MATLAB时间序列预测Prediction of time series with NAR neural network
    因素空间发展评述
    ps 证件照(1,2寸)
    kali linux wmtools安装
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14165016.html
Copyright © 2011-2022 走看看