【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;

}
相关推荐
liu****3 小时前
13.数据在内存中的存储
c语言·开发语言·数据结构·c++·算法
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——数青蛙
算法·leetcode·动态规划·结构与算法
渡我白衣3 小时前
并行的野心与现实——彻底拆解 C++ 标准并行算法(<execution>)的模型、陷阱与性能真相
java·开发语言·网络·c++·人工智能·windows·vscode
闻缺陷则喜何志丹3 小时前
【几何】二维矢量叉乘、正弦定理、三维叉乘及鞋带公式(高斯面积公式)
c++·数学·正弦定理·鞋带公式·矢量叉乘·简单多边形面积
liu****3 小时前
15.自定义类型:联合和枚举
数据结构·c++·剪枝
冉佳驹3 小时前
C++ ——— 动态内存管理和泛型编程的核心机制
c++·delete·模板·new·operator new·operator delete·定位 new
程序猿编码3 小时前
恶意软件分析工具:ELF二进制文件的感染与分析原理(C/C++代码实现)
c语言·c++·网络安全·信息安全·elf·shellcode
资深低代码开发平台专家3 小时前
通用编程时代正在向专用化分层演进
java·大数据·c语言·c++·python
Wild_Pointer.3 小时前
项目实战:使用QCustomPlot实现多窗口绘制数据(支持GPU加速)
c++·qt·gpu算力
CoderYanger4 小时前
动态规划算法-简单多状态dp问题:12.打家劫舍Ⅱ
开发语言·算法·leetcode·职场和发展·动态规划·1024程序员节