题解 | #反转链表#

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

1. 递归

import sys
sys.setrecursionlimit(10000)  
# 经测试python3解释器默认递归最大深度为3000,所以当链表长度大于3000的时候,会引发RecursionError异常
class Solution:
    def ReverseList(self , head: ListNode) -> ListNode:
        # write code here
        if head is None or head.next is None:
            return head
        next_ = head.next
        reverse = self.ReverseList(next_)
        next_.next = head
        head.next = None
        return reverse

2.遍历翻转

class Solution:
    def ReverseList(self , head: ListNode) -> ListNode:
        # write code here
        new_head = None
        while head:
            tmp = head.next
            head.next = new_head
            new_head = head
            head = tmp
        return new_head
全部评论

相关推荐

2024-12-29 15:37
已编辑
西华大学 图像识别
程序员牛肉:去不了,大厂算法卡学历吧
点赞 评论 收藏
分享
冰皮月饼_FLORRIEEE:你是准备投产品嘛?可以重新整理一下实习的bulletpoint,侧重描述你的工作所带来的结果收益,不要只写泛泛的内容(比如改写通过xx数据分析,提升xx),产品的价值并不在处理和分析数据的过程
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务