【c++&Leetcode】206. Reverse Linked List

问题入口

time complexity: O(n), space complexity:O(1)

cpp 复制代码
ListNode* reverseList(ListNode* head) {
    ListNode* prev = nullptr;
    ListNode* curr = head;
    while(curr){
        ListNode* forward = curr->next;
        curr->next = prev;
        prev = curr;
        curr = forward;
    }
    return prev;
}

time complexity: O(n), space complexity:O(n)

cpp 复制代码
ListNode* reverseList(ListNode* head) {
    if(head == NULL || head->next == NULL) 
        return head;
    
    ListNode* tail = reverseList3(head->next);
    head->next->next = head;
    head->next = nullptr;
    return tail;
    
}

要计算给定"reverseList"函数的空间复杂度,让我们分析内存使用情况:

1.函数调用堆栈:

-该函数是递归的,每次递归调用都会向调用堆栈添加一个新帧。

-递归的深度取决于链表的长度。

-在每个递归级别,函数都使用常量空间(局部变量:"tail"、"head")。

-因此,调用堆栈贡献的空间复杂度是O(n),其中n是链表的长度。

2.局部变量(`tail`,`head`):

-该函数为每个递归级别使用两个本地指针("tail"和"head")。

-这些变量所使用的空间在每个级别上都是恒定的。

-由于递归的深度是O(n),因此这些变量贡献的空间复杂度也是O(n)。

3.总体空间复杂性:

-空间复杂性的主要因素是递归导致的调用堆栈。

-因此,"reverseList3"函数的总体空间复杂度为O(n),其中n是链表的长度。

总之,由于递归调用堆栈,空间复杂度为O(n)。每个级别的递归都贡献了恒定的空间,但级别的数量与链表的长度成比例。

待完成

cpp 复制代码
ListNode* reverseList(ListNode* head) {
    
    if(head!= nullptr)//head->next!= NULL occurs member access within null pointer of type 'ListNode' ... 
    {   
        ListNode* tail_to_head = head;
        while(tail_to_head->next != nullptr )
            tail_to_head = tail_to_head->next;

        ListNode* temp = tail_to_head;
        
        for (ListNode* current = head; head != temp ; current = head)
        {
            while(current->next != temp)
                current = current->next;
            
            temp->next = current;
            temp = temp->next;
        }
        head->next = nullptr;
        return tail_to_head;
    }
    return nullptr;

}
相关推荐
BizzZ_30 分钟前
C++(22)——类型转换和IO流
开发语言·c++
青梅味猪大肠3 小时前
【深入浅出C++】为什么虚表指针可以解决菱形继承
开发语言·c++
Lhan.zzZ4 小时前
QML 组件库:VS2022 + Qt 静态库方案
开发语言·c++·qt·visual studio
一木 之林6 小时前
五、C++ 新特性、关键字与编译原理(进阶)(二)
java·开发语言·c++
OPEN-F7 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
闭月之泪舞7 小时前
C++编程学习
c++·学习
带多刺的玫瑰8 小时前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展
圣保罗的大教堂8 小时前
leetcode 877. 石子游戏 中等
leetcode
哭泣方源炼蛊8 小时前
并查集进阶 P1(带权并查集,并查集分类)
数据结构·c++·算法·二进制·带权并查集
小小龙学IT10 小时前
ONNX Runtime 开源 AI 推理引擎深度解析:从模型部署到边缘 AI 加速的全栈实战
c++·人工智能·开源