基于Python实现2种反转链表方法代码实例
作者:孔子?孟子?小柱子! 时间:2021-11-27 21:19:02
题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路:
主要需要注意反转过程中不要丢了节点。可以使用两个指针,也可以使用三个指针。
Python解法一:
class Solution:
def reverseList(self, head):
cur, prev = head, None
while cur:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev
Python解法二:
class Solution:
def reverseList(self, head):
if head == None or head.next == None:
return head
prev = None
cur = head
post = head.next
while post:
cur.next = prev
prev = cur
cur = post
post = post.next
cur.next = prev
return cur
来源:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13232395.html
标签:Python,反转,链表
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实战项目用PyQt5制作漫画脸GUI界面
2023-07-05 13:17:19
![](https://img.aspxhome.com/file/2023/9/59309_0s.png)
PHP实现定时生成HTML网站首页实例代码
2023-06-12 05:39:40
Python try except异常捕获机制原理解析
2023-04-12 20:00:35
![](https://img.aspxhome.com/file/2023/5/70855_0s.png)
Python3 扫描库文件并获取版本号信息的操作方法
2023-08-11 19:14:17
![](https://img.aspxhome.com/file/2023/3/60943_0s.png)
对Python发送带header的http请求方法详解
2022-02-06 11:44:59
Pytorch实现Fashion-mnist分类任务全过程
2023-07-14 05:12:47
![](https://img.aspxhome.com/file/2023/3/62323_0s.png)
Python3实现的爬虫爬取数据并存入mysql数据库操作示例
2022-11-06 15:18:59
![](https://img.aspxhome.com/file/2023/1/66351_0s.png)
从mysql到oracle你必须了解的50件事儿
2010-08-05 14:36:00
利用python解决mysql视图导入导出依赖的问题
2023-10-28 07:27:38
PHP simplexml_load_string()函数实例讲解
2023-07-09 07:19:28
![](https://img.aspxhome.com/file/2023/1/55401_0s.png)
php广告加载类用法实例
2023-11-14 14:56:53
如何编写一个过滤掉HTML代码的函数?
2009-11-08 18:53:00
在JScript中使用RecordSet对象的GetRows方法
2008-01-16 13:12:00
Python爬虫抓取技术的一些经验
2021-06-09 12:02:23
![](https://img.aspxhome.com/file/2023/0/76760_0s.jpg)
python关键字传递参数实例分析
2023-08-24 04:28:34
如何实现网上站点维护?
2010-05-24 18:35:00
ASP中Utf-8与Gb2312编码转换乱码问题的解决方法 页面编码声明
2012-11-30 20:45:55
python中get和post有什么区别
2022-04-17 16:45:15
微信跳一跳辅助python代码实现
2023-03-26 15:25:50
HTML编辑器FCKeditor使用详解
2010-02-28 12:30:00
![](https://img.aspxhome.com/file/UploadPic/20102/28/fckeditor-87s.gif)