力扣刷题-热题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  
相关推荐
x_xbx1 分钟前
LeetCode:53. 最大子数组和
算法·leetcode·职场和发展
菜菜小狗的学习笔记3 分钟前
剑指Offer算法题(一)数组与矩阵
线性代数·算法·矩阵
仰泳的熊猫9 分钟前
题目2269:蓝桥杯2016年第七届真题-冰雹数
开发语言·数据结构·c++·算法·蓝桥杯
Yungoal9 分钟前
C++流类继承关系
开发语言·c++
冷徹 .9 分钟前
2023ICPC山东省赛
c++·算法
Sakinol#16 分钟前
Leetcode Hot 100 ——回溯part01
算法·leetcode
乌萨奇也要立志学C++19 分钟前
【Linux】线程池(二)C++ 手写线程池全流程:从核心设计到线程安全、死锁深度解析
linux·c++
feng_you_ying_li21 分钟前
list的介绍与底层实现
数据结构·c++·list
一粒马豆21 分钟前
如何在二维平面内同时体现系列词汇的词频和相关性?
python·平面·数据可视化·词嵌入·降维·chromadb
星轨初途22 分钟前
C++入门基础指南
开发语言·c++·经验分享·redis