力扣刷题-热题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  
相关推荐
源客z7 分钟前
简易 Python 爬虫实现,10min可完成带效果源码
开发语言·爬虫·python
尹劭东10 分钟前
Django 入门实战:从环境搭建到构建你的第一个 Web 应用
后端·python·django
玖玖passion25 分钟前
排序专题
算法
kuan_li_lyg26 分钟前
MATLAB - 小车倒立摆的非线性模型预测控制(NMPC)
开发语言·算法·matlab·机器人·mpc·模型预测控制·倒立摆
微凉的衣柜31 分钟前
VICP(Velocity-based ICP):通过运动校准实现精准姿态估计
人工智能·算法·计算机视觉
爬虫程序猿1 小时前
动态加载内容时selenium如何操作?
python·selenium·测试工具
灏瀚星空1 小时前
画布交互系统深度优化:从动态缩放、小地图到拖拽同步的全链路实现方案
经验分享·笔记·python·microsoft·交互
lkbhua莱克瓦241 小时前
用c语言实现——一个带头节点的链队列,支持用户输入交互界面、初始化、入队、出队、查找、判空判满、显示队列、遍历计算长度等功能
c语言·数据结构·程序人生·算法·链表·交互·学习方法
满怀10151 小时前
【Python进阶】数据可视化:Matplotlib从入门到实战
python·信息可视化·数据分析·matplotlib·数据可视化
虾球xz1 小时前
游戏引擎学习第239天:通过 OpenGL 渲染游戏
c++·学习·游戏·游戏引擎