-
代码:
#递归 class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ # 递归终止条件是当前为空,或者下一个节点为空 if(head==None or head.next==None): return head # 这里的cur就是最后一个节点 cur = self.reverseList(head.next) # 如果链表是 1->2->3->4->5,那么此时的cur就是5 # 而head是4,head的下一个是5,下下一个是空 # 所以head.next.next 就是5->4 head.next.next = head # 防止链表循环,需要将head.next设置为空 head.next = None # 每层递归函数都返回cur,也就是最后一个节点 return cur
LeetCode206反转链表
最新推荐文章于 2021-11-19 10:11:20 发布