最近在学习生成器,生成器中有个递归式生成器,一直搞不懂就去学习了下递归
参考链接:https://blog.youkuaiyun.com/storyfull/article/details/102671946
对这个文档中的反转链表的代码一直有几个地方不明白:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def ReverseList(self, pHead):
if pHead is None:
return None
if pHead.next is None:
return pHead
last_node = self.ReverseList(pHead.next)
# print(last_node.val)
pHead.next.next = pHead
pHead.next = None
return last_node #一直向上传递的n5,最后再在调用函数处经给print打印出来
def print_list(self, node): # 打印测试
if node is None:
return None
while node:
print(node.val, end="")
node = node.next
print()
if __name__ == '__main__':
n1 = ListNode(1) # 依次实例5个结点
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n1.next = n2 # 依次将结点链接起来,形成一个链表
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = None
obj = Solution()
# print(obj.ReverseList(n1).next.val)
# obj.print_list(n1) # 1 2 3 4 5
obj.print_list(obj.ReverseList(n1)) # 5 4 3 2 1
1.初始化的函数里定义了val和next分别代表什么
这里的初始化是初始化独立的结点,定义了两个指针,val指向传过来的参数x ,next指向none,x是一个独立的解点
2.pHead.next.next = pHead代码的意义
调用ReverseList这个函数,传参pHead,在这里就是n1,即n1指向的1, pHead.next就是传入的这个指针的下一个参数,当代码运行到再次调用ReverseList这个函数的地方时,会暂停阻塞,传递n2给ReverseList这个函数,依次类推,直到传递n5,因为触发了if pHead.next is None: return pHead会返回n5,这样就开始回的过程,回到上一层即phead=n4的这一层,继续从之前暂停阻塞的地方开始运行,会把n5的值即5返回给 last_node
pHead.next.next = pHead就是把n4.next=n5,n5.next=n4,改变指向
pHead.next = None就是n4.next指向none
以此类推,直到运行到外层n1,所有的指向就会反转
3.return在此处的意义
return pHead是递归触发回的动作,因为n5.next指向none,所以就会返回n5,把last_node 指向5
return last_node如果不加这个的话,在第5层返回了n5,这个时候第四层就会从暂停阻塞的地方开始执行,但是第四层没有return,所以就不会返回值,加上这个是为了一路返回n5,最后再调用print_list打印反转之后的结果。
4.print_list的意义
接收n5,触发while循环,print打印出n5.val,再取n5.next=n4,接着打印,知道node.next=none跳出while循环