[算法题] Reverse Linked List II

题目内容

题目来源:LeetCode

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ? m ? n ? length of list.

题目思路

这里就要接着上一道题来继续做了,上次说到单链表反转的两种方法,三指针法和头插法。这一道题就需要用头插法来做。具体可以参考这个博客:http://blog.csdn.net/feliciafay/article/details/6841115, 非常清晰。

先通过for循环找到需要反转的链表的“head”

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 not head or not head.next:
            return head
        dummy=ListNode(-1)
        dummy.next=head
        h=dummy
        for i in range(m-1):
            h=h.next
        p=h.next
        for i in range(n-m):
            tmp=h.next
            h.next=p.next
            p.next=p.next.next
            h.next.next=tmp
        return dummy.next

第二个for循环中的方法要记住,这是常规的单链表反转方法(也可以用上述博客中的方法,值得学习)。

原文地址:https://www.cnblogs.com/chengyuanqi/p/7163084.html