Clear python solution


  • 0
    Z

    Solution is shown below and explained with the comments.

    # 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
            """
            # set up sentinel node
            sentinel = ListNode(None)
            sentinel.next = head
            # initialize
            counter = 0
            cur = sentinel
            front = cur.next
            # loop forward unitl m
            while counter < m:
            	if counter == m-1:
            		node_before_m = cur # record to connect n
            	prev = cur
            	cur = front
            	front = cur.next
            	counter += 1
            node_m = cur # record m
            while counter < n:
            	prev = cur
            	cur = front
            	front = cur.next
            	cur.next = prev
            	counter += 1
            # connect two ends
            node_m.next = front
            node_before_m.next = cur
            if m == 1:
            	head = cur
            return head
            # run in 42 ms
    

Log in to reply
 

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