力扣刷题-热题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  
相关推荐
不搞学术柒柒19 分钟前
《分词算法大揭秘:BPE、BBPE、WordPiece、ULM常见方法介绍》
算法
橘颂TA41 分钟前
【C++】数据结构 九种排序算法的实现
数据结构·c++·排序算法
安装虚拟机的老师傅43 分钟前
当插入排序遇上“凌波微步“——希尔排序的奇幻漂流
数据结构·算法·排序算法
大魔王(已黑化)1 小时前
LeetCode —— 572. 另一棵树的子树
c语言·数据结构·c++·算法·leetcode·职场和发展
机器学习之心HML1 小时前
JCRQ1河马算法+消融实验!HO-CNN-LSTM-Attention系列四模型多变量时序预测,作者:机器学习之心
算法·机器学习·cnn
byte轻骑兵1 小时前
【C++类和数据抽象】消息处理示例(2)
开发语言·c++
一个天蝎座 白勺 程序猿1 小时前
Python爬虫(11)Python数据存储实战:深入解析NoSQL数据库的核心应用与实战
开发语言·python·nosql
千里镜宵烛1 小时前
C++ 红黑树
java·开发语言·c++
敲上瘾1 小时前
高并发内存池(五):性能测试与性能优化
c++·功能测试·缓存·性能优化·线程·高并发内存池
愚润求学1 小时前
【C++11】包装器:function 和 bind
开发语言·c++·笔记·c++11