力扣刷题-热题100题-第23题(c++、python)

206. 反转链表 - 力扣(LeetCode)https://leetcode.cn/problems/reverse-linked-list/solutions/551596/fan-zhuan-lian-biao-by-leetcode-solution-d1k2/?envType=study-plan-v2&envId=top-100-liked

常规法

记录前一个指针,当前指针,后一个指针,遍历链表,改变指针的指向。

复制代码
//c++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        ListNode *pre=nullptr;
        while(head)
        {
            ListNode *nex=head->next;
            head->next=pre;
            pre=head;
            head=nex;
        }
        return pre;
    }
};

#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]:
        pre=None
        while head:
            nex=head.next
            head.next=pre
            pre=head
            head=nex
        return pre  

递归法

对于每一个元素的下一个的下一个要指向自己,自己再指向空,递归进去得到头指针。

复制代码
//c++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        if(!head||!head->next)  return head;
        ListNode * ne=reverseList(head->next);
        head->next->next=head;
        head->next=nullptr;
        return ne;
    }
};

#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 not head or not head.next:
            return head
        new=self.reverseList(head.next)
        head.next.next=head;
        head.next=None;
        return new  
相关推荐
MemoriKu2 分钟前
Flutter 本地 AI 相册工程收口:从屏幕常亮、标签体系到照片属性后台队列
大数据·人工智能·python·flutter·elasticsearch·搜索引擎·数据库架构
2401_8856651910 分钟前
基于OpenCV的模板匹配OCR实战:银行卡与身份证数字识别完整教程
人工智能·python·opencv·计算机视觉·ocr
装不满的克莱因瓶10 分钟前
了解3D卷积原理——从空间感知到时空建模的深度学习核心算子
人工智能·pytorch·python·深度学习·机器学习·3d·ai
凡人叶枫16 分钟前
Effective C++ 条款40:明智而审慎地使用多重继承
java·数据库·c++·嵌入式开发·effective c++
仍然.21 分钟前
算法题目---BFS解决最短路问题
算法·宽度优先
ShineWinsu22 分钟前
对于Linux:线程局部存储(TLS)和线程封装的解析
linux·c++·面试·线程·tls·线程封装·线程局部存储
工头阿乐22 分钟前
使用Conan构建现代C++项目:完整指南
开发语言·c++
渡众机器人22 分钟前
第八届全球校园人工智能算法精英大赛-算法应用赛-空地协同侦排挑战赛规则
人工智能·算法
wayz1134 分钟前
Overlap:HWMA(Holt-Winter移动平均线)技术指标详解
算法·金融·数据分析·量化交易·特征工程
cup1140 分钟前
[开源] Memory Checker:极致轻量的 Windows 托盘内存监测工具,告别内存焦虑
python·内存·工具·任务管理器·托盘