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

leetcode 206. 反转链表

题目描述:

迭代法:

/*** 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) {ListNode* pre = nullptr;ListNode* cur = head;while(cur){ListNode* temp = cur->next;cur->next = pre;pre = cur;cur = temp;}return pre;}
};

递归法

和上面的迭代法一一对应的递归代码:

/*** 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) {return reverse(head,nullptr);}ListNode* reverse(ListNode* cur,ListNode* pre){if(cur == nullptr)return pre;ListNode* temp = cur->next;cur->next = pre;return reverse(temp,cur);}
};

 另一种写法

/*** 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 || !head->next){return head;}ListNode* newHead = reverseList(head->next);head->next->next = head;head->next = nullptr;return newHead;}
};
http://www.xdnf.cn/news/2649.html

相关文章:

  • 湖北理元理律师事务所:债务管理领域的平台化创新探索
  • 回归预测 | Matlab实现DBO-LightGBM蜣螂算法优化轻量级梯度提升机多输入单输出回归预测,作者:机器学习之心
  • 嵌入式开发面试典型编程题解析:排序算法、指针操作、字符处理、递归原理等基础原理的深度解析。
  • 第33周JavaSpringCloud微服务 分布式综合应用
  • echarts+标签+指引线
  • 【javascript】竞速游戏前端优化:高频操作与并发请求的解决方案
  • 开源模型应用落地-全能音频新纪元-Kimi-Audio-7B-Instruct-重塑多模态交互边界
  • Transformer数学推导——Q29 推导语音识别中流式注意力(Streaming Attention)的延迟约束优化
  • 核心要点:线程
  • 解决MacOS端口被占用问题
  • 升级xcode15 报错Error (Xcode): Cycle inside Runner
  • Visual Studio 技能:调整软件界面布局
  • 区块链vs实体经济:一场金融、医疗、政务与物流的“效率革命”
  • C++——入门基础
  • 人工智能大语言模型与AI芯片新进展:技术演进与商业化路径
  • 防火墙拦截DNS请求-原理解析
  • 如何快速在idea中希望Spark程序
  • el-transfer穿梭框数据量过大的解决方案
  • Deepseek 生成新玩法:从文本到可下载 Word 文档?思路与实践
  • 【angular19】入门基础教程(二):组件的创建与使用
  • CSdiy java 05
  • Redo log,Undo log和binlog
  • 蚁群算法是一种模拟蚂蚁觅食行为的优化算法,适合用于解决旅行商问题(TSP)
  • TCP vs UDP:核心区别、握手过程与应用场景(附对比图)
  • 零成本AI抠图终极指南:蓝耘元生代AIDC OS+ComfyUI实现商业级效果
  • 呼叫中心系统:重塑企业沟通效率的核心引擎
  • 灾情分析报告数据集制作
  • 跟着文档学Vuex(一):什么是Vuex
  • WP记录。
  • 单元测试总结