1. 程式人生 > >leetcode 92. 反轉連結串列 II (python)

leetcode 92. 反轉連結串列 II (python)

這道題目提供一個簡單的思路,首先把所有連結串列壓入一個列表裡,然後反轉相應的位置。建立新的連結串列。
class Solution:
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if head ==None:
            return 
        if m ==n:
            return head        
        stack = []
        first = ListNode(0)
        while head:
            stack.append(head.val)
            head = head.next
        stack[m-1:n] = reversed(stack[m-1:n])
        res = first
        while stack:
            first.next = ListNode(stack.pop(0))
            first = first.next
        return res.next