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

总结

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

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

相关推荐
ctlover3 小时前
排序与查找算法详解
开发语言·python
用户8356290780513 小时前
如何使用 Python 给 Word 文档添加水印
后端·python
YYYing.3 小时前
【C++进阶系列 (七)】C++ RTTI 深度剖析:从 typeid 到 dynamic_cast 的底层之旅
开发语言·c++·c/c++·rtti
泡干脆面就番茄4 小时前
深度学习:PyTorch框架初识——MNIST手写数字识别
python·深度学习
shirsl4 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法
门思科技4 小时前
开源网关有哪些:主流类型梳理
网络·python·物联网
szephyr4 小时前
Python 爬虫合规与反爬实战:从 requests 到 Playwright
爬虫·python·requests·playwright·反爬
木子算法4 小时前
非凸、离散、还耦合:论文里的求解方法是一条四步流水线
人工智能·算法·目标跟踪
E-iceblue4 小时前
Excel 列转行/行列转换全指南:从 4 种常见解法到 Python 批量自动化
python·excel·python库·spire.xls
虚无的纽扣4 小时前
【力扣刷题】第二天:无重复字符的最长字串、移动零问题
算法·leetcode·排序算法