24.反转链表

本文介绍如何反转链表,通过创建3个指针处理节点关系。同时,解析了反转链表过程中可能出现的错误:空指针异常和环形链表导致的无限循环问题,并提供了相应的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

输入一个链表,反转链表后,输出新链表的表头。

思路:创建3个指针,分别指向前一个节点,当前节点和下一个节点,以防止反转链表的过程中出现断裂。

python题解:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead:
            return None
        pPre=None
        pNode=pHead
        pReHead=ListNode(None)
        while pNode:
            pNext=pNode.next
            if not pNext:
                pReHead=pNode
            pNode.next=pPre
            pPre=pNode
            pNode=pNext
        return pReHead

 

错误一:

在上述代码中如果pPre=ListNode(None),那么会告诉你

用例:
{1,2,3,4,5}

对应输出应该为:

{5,4,3,2,1}

你的输出为:

{5,4,3,2,1%d format: a number is required, not NoneType

 

错误二,运行超时:

经过检测,发现如果让pPre初始值为头结点,在链表是环形链表时,pNext永远不可能为空,这样无法退出循环,无法终止。但如果pPre初始为空,那么对pNext判空的话是很容易进行的。

举个例子:

 

###这个代码在牛客上运行超时,就是因为没能跳出环形链表
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead:
            return None
        pPre = pHead
        pNode = pHead.next
        pReHead = ListNode(None)
        while pNode:
            pNext = pNode.next
            if not pNext:
                pReHead = pNode
            pNode.next = pPre
            pPre = pNode
            pNode = pNext
        return pReHead

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值