Leetcode 92:反转链表 II(最详细解决方案!!!)

反转从位置 mn 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ mn ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

解题思路

由于这个问题没有给出限定条件,所以我们必须要在代码中排除一些可能。

if head == None or head.next == None or m >= n or m < 0 or n < 0:
	return head

另外对于m,n超出listNode长度的情况,返回head。而对于m小于listNode长度,而n大于listNode长度,这种情况,我们只反转[m, len(listNode)]部分。

代码写起来比较容易,首先把precur移动到指定位置,然后就是Leetcode 206:反转链表(最详细解决方案!!!)t1t2记录precur反转前的位置)

t1   t2       pre  cur  lat
1 -> 2 <- 3 <- 4    5 -> null

接着t1.next=pret2.next=cur

t1   t2       pre  cur  lat
     ----------------
     |              |
1    2 <- 3 <- 4    5 -> null
|              |
----------------
class Solution:
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if head == None or head.next == None or m >= n or m < 0 or n < 0:
            return head

        pre = None
        cur = head
        i = 1
        while i < m and cur != None:
            pre = cur
            cur = cur.next
            i += 1

        t1 = pre
        t2 = cur

        while i <= n and cur != None:
            lat = cur.next
            cur.next = pre
            pre = cur 
            cur = lat
            i += 1

        if m == 1:
            t2.next = cur
            return pre

        t1.next = pre
        t2.next = cur 
        return head

当然我们这里有一个更好的做法,通过构建一个head listNode,这样我们就不用单独讨论m==1的情况

class Solution:
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if head == None or head.next == None or m >= n or m < 0 or n < 0:
            return head

        h = ListNode(-1)
        h.next = head
        pre = h
        cur = head
        i = 1
        while i < m and cur != None:
            pre = cur
            cur = cur.next
            i += 1

        t1 = pre
        t2 = cur

        while i <= n and cur != None:
            lat = cur.next
            cur.next = pre
            pre = cur 
            cur = lat
            i += 1

        t1.next = pre
        t2.next = cur
        return h.next

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页