92. Reverse Linked List II

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->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL.

Note:

Given m, n satisfy the following condition: 1 ≤ mn ≤ length of list.

Solution:

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        dummy = cur = ListNode(None)
        dummy.next = head
        for _ in xrange(m - 1):
            cur = cur.next
        cur.next = self.reverse(cur.next, n - m + 1)
        return dummy.next

    def reverse(self, head, length):
        pre = None
        cur = head
        for _ in xrange(length):
            nxt = cur.next
            cur.next = pre
            pre, cur = cur, nxt
        head.next = cur
        return pre

results matching ""

    No results matching ""