美文网首页
92. Reverse Linked List II

92. Reverse Linked List II

作者: April63 | 来源:发表于2018-06-19 12:42 被阅读0次

模仿前面reverse nodes in k-group写的,代码如下:

# 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
        pre = dummy
        l = dummy
        r = head
        k = n - m + 1
        pm = m-1
        while n:
            r = r.next
            n -= 1
        while m:
            l = l.next
            m -= 1
        while pm:
            pre = pre.next
            pm -= 1
        pr, curr = r, l
        while k:
            curr.next, curr, pr = pr, curr.next, curr
            k -= 1
        pre.next = pr
        return dummy.next 

相关文章

网友评论

      本文标题:92. Reverse Linked List II

      本文链接:https://www.haomeiwen.com/subject/iajaeftx.html