力扣刷题-热题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  
相关推荐
写代码的小球2 小时前
求模运算符c
算法
tan180°5 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
大千AI助手5 小时前
DTW模版匹配:弹性对齐的时间序列相似度度量算法
人工智能·算法·机器学习·数据挖掘·模版匹配·dtw模版匹配
彭祥.6 小时前
Jetson边缘计算主板:Ubuntu 环境配置 CUDA 与 cudNN 推理环境 + OpenCV 与 C++ 进行目标分类
c++·opencv·分类
烛阴6 小时前
简单入门Python装饰器
前端·python
lzb_kkk6 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
YuTaoShao6 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
好开心啊没烦恼7 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
生态遥感监测笔记7 小时前
GEE利用已有土地利用数据选取样本点并进行分类
人工智能·算法·机器学习·分类·数据挖掘