当前位置: 首页 > 后端技术 > Python

反向链表--reverse

时间:2023-03-25 21:29:38 Python

就位题目描述:输入一个链表,将链表反向后,输出一个新的链表链表不同于数组,每个结点除了数据区之外还有一个指针区,用来存放下一个节点的地址。所以访问单向链表只能从头开始访问。在链表的操作中,需要注意的是,在修改节点指针区时,需要记录后继节点的位置,否则会丢失后继节点。方法:给链表逆序1-->2-->3-->4-->5-->无逆链表5-->4-->3-->2-->1-->None思路:#-*-coding:utf-8-*-#classListNode:#def__init__(self,x):#self.val=x#self.next=Noneclass解决方案:#returnListNodedefReverseList(self,pHead):#在这里写代码cur=pHeadpre=Nonewhilecur.nextisnotNone:lat=cur.nextcur.next=prepre=curcur=latlat=cur.nextcur.next=prereturncur如果这样写,程序会报错。错误提示:您的代码已保存回答错误:您提交的程序没有通过所有的测试用例案例通过率为66.67%Case:{}对应的输出应该是:{}你的输出是:'NoneType'objecthasnoattribute'next'可见当链表为空时,cur.next不存在,改进代码#-*-coding:utf-8-*-#classListNode:#def__init__(self,x):#self.val=x#self.next=Noneclass解决方案:#returnListNodedefReverseList(self,pHead):#在这里写代码cur=pHeadpre=NonewhilecurisnotNone:lat=cur.nextcur.next=prepre=curcur=lat返回pre