Python3实现的反转单链表算法示例

yipeiwu_com5年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

使用python socket分发大文件的实现方法

思路: 使用socket传输文件过程中,如果单次传输每次只能发送一部分数据,如果针对大文件,一次传输肯定是不行的,所以需要我们在传输的时候提前把传输内容的大小先发送给客户端,在客户端循环...

python 集合 并集、交集 Series list set 转换的实例

set转成list方法如下: list转成set方法如下: s = set('12342212')       &n...

Python连接字符串过程详解

这篇文章主要介绍了python连接字符串过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在python中,如果有多个字符串,想...

python 计算文件的md5值实例

较小文件处理方法: import hashlib import os def get_md5_01(file_path): md5 = None if os.path.is...

Python+threading模块对单个接口进行并发测试

Python+threading模块对单个接口进行并发测试

本文实例为大家分享了Python threading模块对单个接口进行并发测试的具体代码,供大家参考,具体内容如下 本文知识点 通过在threading.Thread继承类中重写run(...