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

总结

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

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

相关推荐
VBA633727 分钟前
VBA信息获取与处理专题五第三节:发送带附件的电子邮件
开发语言
元亓亓亓29 分钟前
Leet热题100--208. 实现 Trie (前缀树)--中等
java·开发语言
拾荒的小海螺30 分钟前
C#:OpenCvSharp 实现图像处理的技术指南
开发语言·图像处理·c#
墨染点香1 小时前
LeetCode 刷题【144. 二叉树的前序遍历】
数据结构·算法·leetcode
星空的资源小屋2 小时前
Text Grab,一款OCR 截图文字识别工具
python·django·ocr·scikit-learn
寒秋丶2 小时前
Milvus:Json字段详解(十)
数据库·人工智能·python·ai·milvus·向量数据库·rag
自由随风飘5 小时前
python 题目练习1~5
开发语言·python
cynicme6 小时前
力扣3318——计算子数组的 x-sum I(偷懒版)
java·算法·leetcode
Bony-6 小时前
Go语言完全学习指南 - 从基础到精通------语言基础篇
服务器·开发语言·golang
fl1768318 小时前
基于python的天气预报系统设计和可视化数据分析源码+报告
开发语言·python·数据分析