LeetCode Reverse Linked List II

LeetCode解题之Reverse Linked List II

原题

在只遍历一遍且不申请额外空间的情况下将一个链表的第m到n个元素进行翻转。

注意点:

  • m和n满足如下条件:1 ≤ m ≤ n ≤链表长度

例子:

输入: 1->2->3->4->5->NULL, m = 2, n = 4

输出: 1->4->3->2->5->NULL

解题思路

通过 Reverse Linked List 已经可以实现链表的翻转。看下图,把要翻转的一段先进行翻转,再把它和前后的链表接起来。因为可能要把第一个节点也进行翻转,为了一致性增加一个假的头节点。

reverse-linked-list

AC源码

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def to_list(self):
        return [self.val] + self.next.to_list() if self.next else [self.val]


class Solution(object):
    def reverseBetween(self, head, m, n):
        """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """
        dummy = ListNode(-1)
        dummy.next = head
        node = dummy
        for __ in range(m - 1):
            node = node.next
        prev = node.next
        curr = prev.next
        for __ in range(n - m):
            next = curr.next
            curr.next = prev
            prev = curr
            curr = next
        node.next.next = curr
        node.next = prev
        return dummy.next


if __name__ == "__main__":
    n1 = ListNode(1)
    n2 = ListNode(2)
    n3 = ListNode(3)
    n4 = ListNode(4)
    n5 = ListNode(5)
    n1.next = n2
    n2.next = n3
    n3.next = n4
    n4.next = n5
    r = Solution().reverseBetween(n1, 2, 4)
    assert r.to_list() == [1, 4, 3, 2, 5]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

你可能感兴趣的:(LeetCode,算法,链表,python,翻转)