92. 反转链表 II

题目描述

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

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

示例:

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

我的解法(AC)

  • 注意还要把m-n后面的部分链表拼接上(如果有的话)。
# 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):
            return head

        if(m == 1):
            pre = None
            now = head
            now_count = 1
        else:
            now_count = 2
            pre = head
            now = head.next
            while(now_count < m):
                now = now.next
                pre = pre.next
                now_count += 1

        res_head = None
        res_tail = None
        while(now_count <= n):
            if(not res_head):
                res_tail = now
            temp = now.next
            now.next = res_head
            res_head = now
            now = temp
            now_count += 1
            
        if(res_tail):
            res_tail.next = now
        if(pre):
            pre.next = res_head
            return head
        else:
            return res_head