Leetcode: 206.Reverse List 反转链表
发布日期:2021-09-14 15:33:22 浏览次数:5 分类:技术文章

本文共 679 字,大约阅读时间需要 2 分钟。

Reverse List 反转链表

反转一个单链表。


输入:

1->2->3->4->5->NULL

输出:

5->4->3->2->1->NULL

进阶:

你可以迭代或递归地反转链表。你能否用两种方法解决这道题?


方法一:递归

class Solution {
public: ListNode* reverseList(ListNode* head) {
if(!head||!head->next) return head; ListNode *newhead=reverseList(head->next); head->next->next=head; head->next=NULL; return newhead; }};

方法二:迭代

class Solution {
public: ListNode* reverseList(ListNode* head) {
ListNode *cur=head; while(cur&&cur->next){
ListNode *newhead=cur->next; cur->next=cur->next->next; newhead->next=head; head=newhead; } return head; }};

转载地址:https://blog.csdn.net/weixin_42490152/article/details/101601588 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:腾讯游戏学院:实时图形渲染管道
下一篇:Leetcode: 148.Sorted List 排序链表

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月06日 19时07分24秒