当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3实现的反转单链表算法示例

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

2019年03月19日  | 移动技术网IT编程  | 我要评论

欺负小苍兰,我的女友是机器人国语,温州社区

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网