渐渐地,那原本被夜幕笼罩的天空出现了微明。一颗颗启明星逐渐变得苍白无力,在浅浅的日光的照射下,胆怯的它们终于退却了。随着启明星的消失,害羞的太阳射出了几道耀眼的金光。
本文实例讲述了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程序设计有所帮助。
到此这篇关于Python3实现的反转单链表算法示例就介绍到这了。抱最大的希望,为最大的努力,做最坏的打算。更多相关Python3实现的反转单链表算法示例内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!




