leetcode之hot100---206反转链表(C++)

思路一:迭代

遍历链表,逐步反转每个节点的指针方向

cpp 复制代码
/**
 * 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 == nullptr){
            return nullptr;
        }
        ListNode* front = nullptr;//用于保存反转链表过程中的前驱节点,初始为空
        ListNode* current = head;//用于保存当前节点,初始为头节点
        //遍历链表
        while(current != nullptr){
            // 保存当前节点的下一个节点,防止丢失链表后续部分
            ListNode* next = current->next;
            //反转链表,使当前节点的后继为之前的前驱
            current->next = front;
            //更新前驱
            front = current;
            //更新当前节点
            current = next;
        }
        //返回反转链表的头结点
        return front;
        
    }
};
  • 时间复杂度:O(N)
  • 空间复杂度:O(1)

思路二:递归

不断递归调用该函数,使当前节点的后继的后继为当前节点

例如:1 - > 2 - > 3 - > 4

当 当前节点为 1 时,我们需要先反转链表的一部分1 - > 2

此时需要将 2 的后继修改为1 ,对应代码head->next->next = head;

同时需要将1 - > 2 之间断开,对应代码head->next = nullptr;

cpp 复制代码
/**
 * 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 == nullptr){
            return nullptr;
        }
        if(head->next == nullptr){
            return head;
        }
        ListNode* newHead = reverseList(head->next);
        head->next->next = head;//使当前节点的后继的后继为当前节点
        head->next = nullptr;//断链
        //返回反转链表的头结点
        return newHead;
        
    }
};
  • 时间复杂度:O(N)
  • 空间复杂度:O(N)
相关推荐
沐怡旸8 分钟前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4163 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥6 小时前
C++ std::set
c++
Fanxt_Ja6 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下6 小时前
最终的信号类
开发语言·c++·算法
博笙困了7 小时前
AcWing学习——差分
c++·算法
青草地溪水旁7 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁7 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥7 小时前
C++ std::vector
c++
zl_dfq7 小时前
C++ 之【C++11的简介】(可变参数模板、lambda表达式、function\bind包装器)
c++