力扣刷题-热题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  
相关推荐
睡觉就不困鸭4 分钟前
第14天 四数之和
数据结构·算法
云泽80817 分钟前
二叉树高阶笔试算法题精讲(一):序列化、层序遍历、LCA 与 BST 转换
数据结构·c++·算法
weixin_3812881825 分钟前
Layui怎么在表格标题栏中嵌入一个迷你的HTML搜索表单
jvm·数据库·python
再卷也是菜26 分钟前
算法提高篇(3)线段树(下)
算法
m0_7478545228 分钟前
C# 文件系统Filter Hook C#能否在用户模式下拦截文件系统调用
jvm·数据库·python
嘻嘻哈哈樱桃31 分钟前
牛客经典101题题解集--二叉树
java·数据结构·python·算法·leetcode·职场和发展
6Hzlia34 分钟前
【Hot 100 刷题计划】 LeetCode 98. 验证二叉搜索树 | C++ 指针边界法
c++·算法·leetcode
Frank学习路上34 分钟前
【Python】应用:发布pyproject.toml格式包到 PyPI
开发语言·chrome·python
AI科技星42 分钟前
算子数学|独立完整学科章节(百条原创公式· ROOT传世定稿)
大数据·算法·机器学习·数学建模·数据挖掘·量子计算
阿标的博客43 分钟前
Python学习(三):Python程序的运行方式
开发语言·python·学习