您的位置:首页 > 游戏 > 游戏 > 百度2345网址导航_上海平面设计师招聘_bt磁力搜索引擎索引_软文推广代写代发

百度2345网址导航_上海平面设计师招聘_bt磁力搜索引擎索引_软文推广代写代发

2025/5/2 3:47:04 来源:https://blog.csdn.net/weixin_41554427/article/details/147597108  浏览:    关键词:百度2345网址导航_上海平面设计师招聘_bt磁力搜索引擎索引_软文推广代写代发
百度2345网址导航_上海平面设计师招聘_bt磁力搜索引擎索引_软文推广代写代发

题目描述:

迭代法:

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com