封面

LeetCode 题解 · 反转链表

笔记日期
# LeetCode
# Python
# 链表

在纸上写 1 → 2 → 3,把 1 的箭头擦掉,程序就再也找不到 2 了。这题只要记住这个小动作:先收好下一站的地址,然后才转身。

第一轮 curr=1、prev 为空,收好 2,让 1 指向空。第二轮收好 3,让 2 指向 1。最后让 3 指向 2,再往后没有新节点,prev 手里握着的 3 就是新链头。

class Solution:
    def reverseList(self, head):
        prev, curr = None, head
        while curr is not None:
            following = curr.next
            curr.next = prev
            prev, curr = curr, following
        return prev

空链返回 None,单节点翻过来还是它自己。所有原节点都保留下来,变化的只有箭头,旧头会变成新尾。时间 O(n),额外空间 O(1)。

LeetCode 第 206 题

返回 LeetCode 题单 →