节点类:
1 class ListNode(object): 2 def __init__(self, x): 3 self.val = x 4 slef.next = None
反转单向链表的函数如下:
1 def reverseList(head): 2 pre = None 3 while head is not None: 4 next = head.next 5 head.next = pre 6 pre = head 7 head = next 8 return pre
第一次循环
第一步:
next = head.next
将 head.next 赋值给 next 变量,也就是说 next 指向了节点2,先将节点2 保存起来。
第二步:
head.next = pre
将 pre 变量赋值给 head.next,即 节点1 指向了 None
第三步:
pre = head
将 head 赋值给了 pre,即 pre 指向节点1,将节点1 设为“上一个节点”
第四步:
head = next
将 next 赋值给 head,即 head 指向了节点2。将节点2 设为“头节点”
第一次循环完毕,进入第二次循环。
第二次循环开始
第一步:
next = head.next
将 head.next 赋值给 next 变量,也就是 next 指向了节点3,先将节点3 保存起来。
第二步:
head.next = pre
将 pre 赋值给 head.next,pre 在上一次循环的时候指向了节点1,那么这一步的意义就是节点2 指向了 节点1,完成一次反转
第三步:
pre = head
将 head 赋值给了 pre,即 pre 指向节点2,将节点2 设为“上一个节点”
第四步:
head = next
将 next 赋值给 head,即 head 指向了节点3。将节点3 设为“头节点”
第二次循环完毕,以此类推!第三次第四次第五次循环。就可以完成翻转
总结
- 保存当前头节点的下一个节点(当前头节点为2,先将节点3 保存起来)
- 将当前头节点的下一个节点指向 “上一个节点”(当前头节点2 指向了 (“上一个节点”)节点1),这一步才是实现反转
- 将当前头节点设置 “上一个节点”(将节点2 设为“上一个节点”)
- 将保存的下一个节点设置 “头节点”(将节点3 设为“头节点”)
原文链接:https://blog.csdn.net/qq_39010254/article/details/89225061