LeetCode31

206.反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

复制代码
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

复制代码
输入:head = [1,2]
输出:[2,1]

示例 3:

复制代码
输入:head = []
输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000
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: Optional[ListNode]) -> Optional[ListNode]:
        if head is None:
            return None
        elif head.next is None:
            return head
        else:
            dummy = ListNode()
            p = head
            while p.next is not None:
                p = p.next
            dummy.next = p
            while 1:
                p = head
                while p.next.next is not None:
                    p = p.next
                p.next.next = p
                p.next = None
                if head.next is None:
                    return dummy.next
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: Optional[ListNode]) -> Optional[ListNode]:
        if head is None:
            return None
        elif head.next is None:
            return head
        else:
            q = None
            p = head
            while p is not None:
                j = p.next
                p.next = q
                q = p
                p = j
            return q

总结

从后往前,不能遍历到最后一个,只能遍历到倒数第二个。

从前往后,需要三个指针,多一个存储下一个节点。

相关推荐
MZ_ZXD0011 小时前
springboot汽车租赁服务管理系统-计算机毕业设计源码58196
java·c++·spring boot·python·django·flask·php
A 计算机毕业设计-小途2 小时前
大四零基础用Vue+ElementUI一周做完化妆品推荐系统?
java·大数据·hadoop·python·spark·毕业设计·毕设
快去睡觉~3 小时前
力扣73:矩阵置零
算法·leetcode·矩阵
岁忧3 小时前
(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
java·c++·leetcode·游戏·go·深度优先
小欣加油3 小时前
leetcode 3 无重复字符的最长子串
c++·算法·leetcode
念念01075 小时前
数学建模竞赛中评价类相关模型
python·数学建模·因子分析·topsis
四维碎片5 小时前
【Qt】线程池与全局信号实现异步协作
开发语言·qt·ui·visual studio
IT码农-爱吃辣条5 小时前
Three.js 初级教程大全
开发语言·javascript·three.js
云天徽上6 小时前
【数据可视化-94】2025 亚洲杯总决赛数据可视化分析:澳大利亚队 vs 中国队
python·信息可视化·数据挖掘·数据分析·数据可视化·pyecharts
☺����6 小时前
实现自己的AI视频监控系统-第一章-视频拉流与解码2
开发语言·人工智能·python·音视频