力扣刷题-热题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  
相关推荐
鲸渔14 分钟前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程
星恒随风22 分钟前
从0实现C++ AI大模型接入SDK(三):环境搭建与ChatSDK快速上手——实现我们的第一个AI聊天程序
linux·开发语言·c++·人工智能·笔记
风落青芜24 分钟前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z1 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah1 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
fengkai45451 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
撸码猿1 小时前
Ladybird 进入 alpha:从零写的浏览器引擎现在能下载了
c++·rust·开源·浏览器·ladybird
用户45428451062812 小时前
一张 3000×2000 的 PSD 为什么 86MB:从体积构成到上传墙
python
草履虫AI课2 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习
用户298698530142 小时前
使用 Python 提取 Word 文档中的文本与图片
后端·python·api