当前位置: 首页 > news >正文

【c++Leetcode】206. Reverse Linked List

问题入口

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

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)

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)。每个级别的递归都贡献了恒定的空间,但级别的数量与链表的长度成比例。

待完成

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

http://www.lryc.cn/news/239770.html

相关文章:

  • [项目管理-33/创业之路-87/管理者与领导者-127]:如何提升自己项目管理的能力和水平
  • 记录一次因内存不足而导致hiveserver2和namenode进程宕机的排查
  • c# 基础语法
  • 【译】什么时候使用 Spring 6 JdbcClient
  • VR全景:赋能城市园区建设,打造3DVR城市名片
  • 孟德尔随机化写作技巧mr
  • 社会媒体营销提问常用的ChatGPT通用提示词模板
  • 智慧储能边缘计算网关应用,提升能源效率
  • 利用 Apache Ranger 管理 Amazon EMR 中的数据权限
  • HarmonyOS(三)—— 应用程序入口—UIAbility
  • Vuetify:定制化、响应式的 Vue UI 库 | 开源日报 No.83
  • 使用PySpark 结合Apache SystemDS 进行信号处理分析 (离散傅立叶变换)的简单例子
  • AT89S52单片机的最小应用系统
  • Pytorch中的tensor维度理解
  • 2019年12月 Scratch(三级)真题解析#中国电子学会#全国青少年软件编程等级考试
  • matlab-实现-BP-神经网络
  • 基于go-zero的rpc服务示例
  • 【算法】奇偶游戏(带权并查集)
  • 补充:linux rsyslog配置多端口监听(基于UDP)
  • 详解StringBuilder和StringBuffer(区别,使用方法,含源码讲解)
  • 九、sdl显示bmp图片
  • ROS设置DHCP option121
  • ④【Set】Redis常用数据类型: Set [使用手册]
  • 助力企业前行——ScalaSpark最佳实践课程
  • pikachu靶场Table pikachu.member doesn’t exist:解决
  • Github Copilot AI编码完成工具
  • android 9 adb安装过程学习(二)
  • Java面试-框架篇-Mybatis
  • java基础-集合
  • 【C++11】auto与decltype关键字使用详解