[LeetCode]题解(python):092-Reverse Linked List II

题目来源:

  https://leetcode.com/problems/reverse-linked-list-ii/


题意分析:

  跟定一个链表,和位置m,n。将m到n的节点翻转。


题目思路:

  和前面全部翻转的类似。


代码(Python):

  

# 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 head == None or head.next == None:
            return head
        ans = ListNode(-1)
        t,ans.next = ans,head
        for i in range(m - 1):
            t = t.next
        tmp = t.next
        for i in range(n- m):
            tmp1 = t.next
            t.next = tmp.next
            tmp.next = tmp.next.next
            t.next.next = tmp1
        return ans.next
        
View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/5088851.html 

原文地址:https://www.cnblogs.com/chruny/p/5088851.html