Leetcode-Reverse Linked List-Python

Reverse Linked List

反转单链表。
Description

iterative:

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

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None
        while head:
            curr = head             # 1
            head = head.next        # 2
            curr.next = prev        # 3
            prev = curr             # 4
        return prev 

解题思路
网上关于反转链表的解题思路大多是只给出了代码而没有附上解释,刚开始看有点晕乎,下面是我的思路:
首先创建一个None节点prev, 然后依次取出原来链表中的元素curr,添加到prev节点的前面(即将取出的curr节点的next节点设置为prev),接着更新prev节点(即将prev节点向前移),总的来说,反转后的链表是从后往前构建出来的。
具体的:(为方便描述,node.val直接用node表示)
initial: 假设原链表=[1, 2, 5], 此时head = 1。令prev = None, prev指向反转后链表的头节点,因此反转后的链表=[]。

step1: 取出原链表的元素,并令curr指向该元素,即curr=head=1
step2: 将head指向下一个元素,即head=2
step3: 将取出的元素curr放到prev的前面,即令curr.next = prev = None,
step4: 更新prev节点, prev=1, 此时反转链表变为[1]

由于head=2不为空,重复开始step1
step1: curr = head = 2
step2: head = 5
step3: curr.next = prev = 1,
step4: prev = 2, 此时反转链表变为[2,1]

step1: curr = head = 5
step2: head = None
step3: curr.next = prev = 2
step4: prev = 5, 此时反转链表变为[5, 2, 1]
由于head为None, 迭代结束,返回prev.

注意

head = head.next        # 2

步骤2的顺序不能错,刚开始我这样写时运行错误,原因是curr和head是指向同一个元素的引用,因此如果先进行步骤3会导致相应的head元素也发生改变。

while head:
            curr = head             # 1
            curr.next = prev        # 3
            head = head.next        # 2
            prev = curr             # 4
        return prev 

猜你喜欢

转载自blog.csdn.net/ddydavie/article/details/77604532