欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-11-14 09:05:17
本文实例讲述了python3实现的反转单链表算法。分享给大家供大家参考,具体如下: 反转一个单链表。 方案一:迭代 # definition for sing...

本文实例讲述了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程序设计有所帮助。