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

总结

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

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

相关推荐
Yu_Mao_Cat2 分钟前
数独求解器3.0 增加latex格式读取
开发语言·python·算法
豆约翰8 分钟前
c#和python互操作实现排序算法可视化
python·c#·排序算法
天若有情6731 小时前
探秘 C++ 计数器类:从基础实现到高级应用
java·开发语言·c++
进击的愤怒1 小时前
GIM发布新版本了 (附rust CLI制作brew bottle流程)
开发语言·后端·rust
x-cmd1 小时前
x-cmd install | cargo-selector:优雅管理 Rust 项目二进制与示例,开发体验升级
开发语言·后端·rust·cargo·示例
inksci1 小时前
Python web 开发 Flask HTTP 服务
python·flask
春生野草1 小时前
如何用JAVA手写一个Tomcat
java·开发语言·tomcat
爱coding的橙子2 小时前
每日算法刷题计划day13 5.22:leetcode不定长滑动窗口最短/最小1道题+求子数组个数越长越合法2道题,用时1h
算法·leetcode·职场和发展
编程绿豆侠2 小时前
力扣HOT100之二叉树: 437. 路径总和 III
算法·leetcode·哈希算法
范纹杉想快点毕业2 小时前
Google C++ Style Guide 谷歌 C++编码风格指南,深入理解华为与谷歌的编程规范——C和C++实践指南
c语言·数据结构·c++·qt·算法