• 边工作边刷题:70天一遍leetcode: day 20-4


    Reverse Linked List II

    要点:和k-group类似,要点上唯一的区别是k-group那题如果不够k个结点,不reverse,所以不能one-pass,这题可以one-pass

    • 已经多次见过了cur,cur.next的模式,cur是pre,cur.next是当前要处理的结点
    • 计数:m:因为要落在开始结点的前一个,所以是从dummy开始,移动次数为m-1(这里记忆方法是移动次数+1是覆盖的结点数,而loop是移动次数>0),java中可以用--m>0来表示,python只能m先-1。n:这里的loop是要处理的结点个数,所以是n-m+1
    • reverse两步走:结点组reverse:切记pre初始为null而不是前一个点,外部连接是分开进行的。对外部连接,只要记住是reverse的过程是不会自动连好外部结点就可以了。
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reverseBetween(self, head, m, n):
            """
            :type head: ListNode
            :type m: int
            :type n: int
            :rtype: ListNode
            """
            dummy = ListNode(0)
            dummy.next = head
            cur = dummy
            n=n-m+1
            m-=1
            while m>0 and cur:
                cur=cur.next
                m-=1
            
            if not cur: return head
            newpre = cur
            pre = None
            cur = cur.next
            while cur and n>0:
                next = cur.next
                cur.next = pre
                pre = cur
                cur = next
                n-=1
            
            newpre.next.next = cur
            newpre.next = pre
            return dummy.next
            
                
    
  • 相关阅读:
    完美数据迁移-MongoDB Stream的应用
    补习系列(3)-springboot中的几种scope
    补习系列(2)-springboot mime类型处理
    hdfs directory item limit
    git-format-patch
    SPARK-18560
    hdfs OutOfMemoryError
    hdfs 路径不支持‘:’
    java.io.UTFDataFormatException: encoded string too long:
    scala-maven-plugin excludes
  • 原文地址:https://www.cnblogs.com/absolute/p/5677954.html
Copyright © 2020-2023  润新知