Skip to content

Latest commit

 

History

History
48 lines (37 loc) · 1.08 KB

92.md

File metadata and controls

48 lines (37 loc) · 1.08 KB

Reverse Linked List II

Description

link


Solution

See Code

注意代码最后两行,拼接的时候,先指定next.next,然后指定next,可以使得不论next接了多少个node,都可以在最后那个node后接上next.next

理解错误,因为pre.next本来就是连在第二部分的最后一段,所以可以直接使用next next的方法来接上第三段


Code

O(n)

class Solution:
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        dummy = pre = ListNode(0)
        dummy.next = head
        for _ in range(m-1):
            pre = pre.next
        cur = pre.next
        # reverse the defined part
        node = None
        for _ in range(n-m+1):
            nxt = cur.next
            cur.next = node
            node = cur
            cur= nxt
        # connect three parts
        pre.next.next = cur
        pre.next = node
        return dummy.next