当前位置:   article > 正文

leetcode 206. 反转链表 python_手撕代码目leetcode 206、反转链表python

手撕代码目leetcode 206、反转链表python

题目描述:

 题解一:

class Solution(object):
    def reverseList(self, head):
        if head==None or head.next==None:
            return head
        pre = None
        cur = head
        nxt = cur.next
        while nxt:
            cur.next = pre
            pre = cur
            cur = nxt
            nxt = nxt.next
        cur.next = pre
        return cur 

 

题解二:递归

1.递归终止条件:输入head为空或head.next为空,返回head

2.递归返回值:反转后的head

3.当前递归:

将head->head.next变为head.next->head

对head.next调用reverseList,得到head.next反转后的结果。

head.next.next变为head

head.next设为空

class Solution(object):
    def reverseList(self, head):
        if head==None or head.next==None:
            return head
        node  = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return node

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/209353?site
推荐阅读
相关标签
  

闽ICP备14008679号