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

总结

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

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

相关推荐
张槊哲7 分钟前
函数的定义与使用(python)
开发语言·python
船长@Quant12 分钟前
文档构建:Sphinx全面使用指南 — 实战篇
python·markdown·sphinx·文档构建
北辰浮光15 分钟前
[Mybatis-plus]
java·开发语言·mybatis
我想进大厂38 分钟前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂43 分钟前
图论---Bellman-Ford算法
数据结构·c++·算法·图论
AIGC大时代1 小时前
高效使用DeepSeek对“情境+ 对象 +问题“型课题进行开题!
数据库·人工智能·算法·aigc·智能写作·deepseek
光而不耀@lgy1 小时前
C++初登门槛
linux·开发语言·网络·c++·后端
lkbhua莱克瓦241 小时前
用C语言实现——一个中缀表达式的计算器。支持用户输入和动画演示过程。
c语言·开发语言·数据结构·链表·学习方法·交友·计算器
Mr__Miss1 小时前
面试踩过的坑
java·开发语言
偶尔微微一笑1 小时前
AI网络渗透kali应用(gptshell)
linux·人工智能·python·自然语言处理·编辑器