栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

力扣 反转链表 Python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣 反转链表 Python

目录

1 题目

2 题解

3 Python


1 题目

2 题解

正常通过遍历的方法是设置指针顺次遍历,然后将指针改变方向就可以。

递归的方式可以先将链表除第一个节点以外的链表反转,然后将第一个节点连接在反转之后的链表上,再将其指针置空。

3 Python

遍历的写法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        #如果链表为空,或者只有一个节点
        if head is None or head.next is None:
            #直接返回就可以
            return head
        #指向前一个节点的指针
        pre=None
        #当前节点指针
        now=head
        while now is not None:
            #记录下一个要移动到的节点
            last=now.next
            #反转
            now.next=pre
            #移动到下一个节点
            pre=now
            now=last
        
        return pre

递归写法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        #如果链表为空,或者只有一个节点
        if head is None or head.next is None:
            #直接返回就可以
            return head
        #反转除第一个节点外的后续链表
        newhead=self.reverseList(head.next)
        #处理第一个节点
        head.next.next=head
        head.next=None
        return newhead

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/916139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号