1. 程式人生 > >Leetcode 92:反轉連結串列 II(最詳細解決方案!!!)

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

如有問題,希望大家指出!!!