python单链表反转循环和递归实现

递归实现

1. 代码

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if pHead is None or pHead.next is None:
            return pHead
        newList = self.ReverseList(pHead.next)
        post = pHead.next #当前节点下一个节点
        post.next = pHead #逆转下一个节点
        pHead.next = None #断开前一个的指向
            
        return newList

2. 图解

 

 

用python特性,交换变量值实现

代码

def reverse(pHead):
    reversed_head = None
    current = pHead
    while current:
        reversed_head, reversed_head.next, current = current, reversed_head, current.next
    return reversed_head

 

循环实现

pre, post两个指针,一个记录前一个节点,一个记录后一个节点

def reverse_for(pHead):
    if pHead is None or pHead.next is None:
        return pHead
    else:
        cur = pHead
        pre = None
        while cur:
            post = cur.next  # post为当前元素的后一个
            cur.next = pre  # 当前元素的后一个设置为pre, 即断开原来的指向
            pre = cur
            cur = post       # 移动当前为下一个
    return pre

 

posted @ 2021-07-12 16:11  水天需  阅读(233)  评论(0编辑  收藏  举报