如何用python创建单链表(Python3实现的反转单链表算法示例)
类别:脚本大全 浏览量:335
时间:2022-01-14 02:21:10 如何用python创建单链表
Python3实现的反转单链表算法示例本文实例讲述了Python3实现的反转单链表算法。分享给大家供大家参考,具体如下:
反转一个单链表。
方案一:迭代
|
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList( self , head): """ :type head: ListNode :rtype: ListNode """ cur, pre = head, None while cur: cur. next , pre, cur = pre, cur, cur. next return pre |
方案二:递归
|
# -*- 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 or not pHead. next : return pHead else : newHead = self .ReverseList(pHead. next ) pHead. next . next = pHead pHead. next = None return newHead |
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/zhenghaitian/article/details/81009682
您可能感兴趣
- python写一个二叉树(Python二叉搜索树与双向链表转换算法示例)
- php大量数据计算有什么技巧(PHP各种常见经典算法总结排序、查找、翻转等)
- php100种算法(php实现的生成排列算法示例)
- php对称算法示例(php解决约瑟夫环算法实例分析)
- python实现螺旋矩阵(Python3实现的旋转矩阵图像算法示例)
- python数据分析删除重复值(Python3实现从排序数组中删除重复项算法分析)
- python动态数组原理(Python实现的旋转数组功能算法示例)
- 淘宝算法推荐逻辑公式(详解淘宝H5 sign加密算法)
- python字符串相似度匹配(Python实现字符串匹配的KMP算法)
- knn算法详细步骤(Python实现KNNK-近邻算法的示例代码)
- python自动解数独教学(Python判断有效的数独算法示例)
- python蓝牙knn算法(python使用KNN算法识别手写数字)
- 基于python的加密算法(python实现维吉尼亚加密法)
- pythonai识别算法(Python3调用百度AI识别图片中的文字功能示例测试可用)
- laravel算法(laravel批量生成假数据的方法)
- C#排序算法的比较
- 红色代表什么(红色代表什么寓意)
- 蓝天代表什么(蓝天代表什么生肖)
- 今天要吃什么(今天要吃什么菜)
- 营养餐是什么(学校营养餐是什么)
- 谁说女子不如男 范冰冰演的武则天只是其一,另外两位你认识吗(谁说女子不如男)
- 杯酒人生---瓦伦丁酒杯和奥丁格啤酒(杯酒人生---瓦伦丁酒杯和奥丁格啤酒)
热门推荐
排行榜
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9