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

}
相关推荐
咸鱼爱学习6 分钟前
【题解】B2613【深基1.习5】打字速度
数据结构·c++·算法
一匹电信狗9 分钟前
【C++】C++风格的类型转换
服务器·开发语言·c++·leetcode·小程序·stl·visual studio
syt_biancheng16 分钟前
C++ 多态(1)
jvm·c++·学习
学学学无无止境1 小时前
力扣-上升的温度
leetcode
std78791 小时前
用C++ 实现屏幕保护程序
开发语言·c++
tumu_C1 小时前
无用知识研究:在trailing return type利用decltype,comma operator在对函数进行sfinae原创 [二]
开发语言·c++·算法
红糖生姜2 小时前
P12874 [蓝桥杯 2025 国 Python A] 巡逻||题解||图论
c++·蓝桥杯·图论
云泽8082 小时前
C/C++内存管理详解:从基础原理到自定义内存池原理
java·c语言·c++
Emilia486.3 小时前
【Leetcode&nowcode&数据结构】顺序表的应用
数据结构·算法·leetcode
小年糕是糕手3 小时前
【数据结构】双向链表“0”基础知识讲解 + 实战演练
c语言·开发语言·数据结构·c++·学习·算法·链表