网络编程
位置:首页>> 网络编程>> Python编程>> 基于Python实现2种反转链表方法代码实例

基于Python实现2种反转链表方法代码实例

作者:孔子?孟子?小柱子!  发布时间:2021-11-27 21:19:02 

标签:Python,反转,链表

题目:

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL

输出: 5->4->3->2->1->NULL

进阶:

你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路:

主要需要注意反转过程中不要丢了节点。可以使用两个指针,也可以使用三个指针。

基于Python实现2种反转链表方法代码实例

基于Python实现2种反转链表方法代码实例

Python解法一:


class Solution:
 def reverseList(self, head):
   cur, prev = head, None
   while cur:
     temp = cur.next
     cur.next = prev
     prev = cur
     cur = temp
   return prev

Python解法二:


class Solution:
 def reverseList(self, head):
   if head == None or head.next == None:
     return head
   prev = None
   cur = head
   post = head.next

while post:
     cur.next = prev
     prev = cur
     cur = post
     post = post.next
   cur.next = prev
   return cur

来源:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13232395.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com