python反转链表_反转链表--原地反转

题目描述:输入一个链表,反转链表后,输出新链表

链表与数组不同,每个结点除数据区外,还存在一个指针区,用来存放下一个结点的地址。

因此,单链表的访问只能从头开始访问。

在对链表操作中,需要注意修改结点指针区时,需要记录下来后继结点的位置,否则会丢失后继结点。

方法:就地逆序

给定链表 1-->2-->3-->4-->5-->None

反转链表 5-->4-->3-->2-->1-->None

思路:

bVbxof1?w=4032&h=3024

# -*- 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

cur = pHead

pre = None

while cur.next is not None:

lat = cur.next

cur.next = pre

pre = cur

cur = lat

lat = cur.next

cur.next = pre

return cur

这么写,程序会报错。错误提示:

您的代码已保存

答案错误:您提交的程序没有通过所有的测试用例

case通过率为66.67%

用例:

{}

对应输出应该为:

{}

你的输出为:

'NoneType' object has no attribute 'next'

可以看出当链表为空时,cur.next 不存在,改进代码

# -*- 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

cur = pHead

pre = None

while cur is not None:

lat = cur.next

cur.next = pre

pre = cur

cur = lat

return pre

bVbxoiO?w=1006&h=132

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值