leetcode Reverse Linked List II -- 重点

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


understanding:

这里要注意加一个dummy node,以及index范围的确定。


my code:

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if m == n:
            return head
        
        count = 1
        
        m_node = head
        dummy_node = ListNode(0)
        pre = dummy_node
        
        while count != m:
            pre = m_node
            m_node = m_node.next
            count += 1
        e1 = pre # end of the 1st seg
        e2 = m_node # end of the 2nd set
        
        count = 1
        while count != n - m + 1:
            
            next_node = m_node.next
            m_node.next = pre
            pre = m_node
            m_node = next_node
            count += 1
        s2 = m_node.next
        m_node.next = pre
        s1 = m_node
        
        e1.next = s1
        e2.next = s2
        
        if m != 1:
            return head
        else:
            return s1

参考 code: http://bookshadow.com/weblog/2015/01/29/leetcode-reverse-linked-list-ii/

你可能感兴趣的:(leetcode Reverse Linked List II -- 重点)