Talk is cheap, show me the code (and DRAWING)


  • 1

    On my way of self-learning, linked list was always a nightmare to me. Hopes the code and this graph (ugh, kind of ugly maybe) can help someone who was just like me.

    class Solution(object):
        def reverseBetween(self, head, m, n):
            """
            :type head: ListNode
            :type m: int
            :type n: int
            :rtype: ListNode
            """
            if not head or m == n: return head
            p = dummy = ListNode(None)
            dummy.next = head
            for i in range(m-1): p = p.next
            tail = p.next
    
            for i in range(n-m):
                tmp = p.next                  # a)
                p.next = tail.next            # b)
                tail.next = tail.next.next    # c)
                p.next.next = tmp             # d)
            return dummy.next
    

    0_1490008790876_reversed_linked_list.jpeg


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.