力扣刷题-热题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  
相关推荐
澈2075 分钟前
堆排序:高效构建大顶堆实战
数据结构·算法·排序算法
架构师老Y6 分钟前
011、消息队列应用:RabbitMQ、Kafka与Celery
python·架构·kafka·rabbitmq·ruby
枫叶林FYL11 分钟前
【Python高级工程与架构实战】项目四:生产级LLM Agent框架:基于PydanticAI的类型安全企业级实现
人工智能·python·自然语言处理
龙腾AI白云12 分钟前
多模大模型应用实战:智能问答系统开发
python·机器学习·数据分析·django·tornado
Hommy8823 分钟前
【开源剪映小助手】配置与部署
python·开源·aigc·剪映小助手
chh56324 分钟前
C++--内存管理
java·c语言·c++·windows·学习·面试
Yungoal25 分钟前
C++ 标准模板库STL(Standard Template Library)
c++·哈希算法·散列表
我真不是小鱼27 分钟前
cpp刷题打卡记录27——无重复字符的最长子串 & 找到字符串中所有字母的异位词
数据结构·c++·算法·leetcode
V搜xhliang024631 分钟前
基于¹⁸F-FDG PET/CT的深度学习-影像组学-临床模型预测非小细胞肺癌脉管侵犯的价值
大数据·人工智能·python·深度学习·机器学习·机器人
XuecWu331 分钟前
原生多模态颠覆Scaling Law?解读语言“参数需求型”与视觉“数据需求型”核心差异
人工智能·深度学习·算法·计算机视觉·语言模型