1. 程式人生 > >【LeetCode 中等題】47-反轉連結串列II

【LeetCode 中等題】47-反轉連結串列II

題目描述:反轉從位置 m 到 n 的連結串列。請使用一趟掃描完成反轉。

說明:
1 ≤ m ≤ n ≤ 連結串列長度。

示例:

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

解法1。為了解決m==1的問題,建立一個頭結點指向head,用兩個指標記錄第m個位置的元素和它的前一個元素,然後該指標往後翻轉n-m+1次,再改變指向關係,如下。

# 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
        """
        if not head or not head.next or m<0 or n<0 or m>n:
            return head
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        cur = head
        i = 1
        while i < m and cur:
            pre = pre.next
            cur = cur.next
            i += 1
        t1 = pre
        t2 = cur
        p = None
        while i <= n and cur:
            tmp = cur.next
            cur.next = p
            p = cur
            cur = tmp
            i += 1
        t1.next = p
        t2.next = cur
        return dummy.next