• 92. 反转链表 II




    方法一:

    class Solution(object):
        def reverseBetween(self, head, m, n):
            """
            :type head: ListNode
            :type m: int
            :type n: int
            :rtype: ListNode
            """
            # 边界处理
            if not head or not head.next or m == n:
                return head
            # 返回值
            ans = ListNode(0)
            ans.next = head
            # 记录第m-1个节点
            pre = ListNode(0)
            for i in range(1, m):
                pre = head
                head = head.next
            # 反转部分的首节点
            prehead = ListNode(0)
            # 记录第n个节点
            pretail = head
            # 开始反转从m到n个节点
            for j in range(m, n + 1):
                temp = head.next
                head.next = prehead
                prehead = head
                head = temp
            # 若不是从首节点开始反转,则拼接前部分未反转的节点
            if m != 1:
                pre.next = prehead
            else:
                ans.next = prehead
            # 若n小于原链表长度,则拼接后部分未反转的节点
            if head:
                pretail.next = head
            return ans.next
    

    方法二:

    class Solution(object):
        def reverseBetween(self, head, m, n):
            """
            :type head: ListNode
            :type m: int
            :type n: int
            :rtype: ListNode
            """
            # 边界处理
            if not head or not head.next or m == n:
                return head
            prehead, cur = None, head
            while m > 1:
                prehead = cur
                cur = cur.next
                m -= 1
                n -= 1
            # one和two分别是遍历指针和前部分不用反转的最后一个节点
            one, two = cur, prehead
            while n:
                temp = cur.next
                cur.next = prehead
                prehead = cur
                cur = temp
                n -= 1
            if two:
                two.next = prehead
            else:
                head = prehead
            one.next = cur
            return head
    
  • 相关阅读:
    设计模式之建造者模式(简单)
    设计模式之简单工厂模式,工厂模式,抽象工厂模式
    设计模式之观察者模式
    Redis java操作客服端——jedis
    Redis基础
    java环境变量配置加maven配置
    设计模式之JDK动态代理
    springboot+mybatis+Thymeleaf
    OS问题管理系统开发
    复制CentOS虚拟机网络配置
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12857070.html
Copyright © 2020-2023  润新知