LeetCode刷题(185)~反转链表【双指针|递归 易错!】

    科技2024-01-31  106

    题目描述

    定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

    示例:

    输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

    限制:

    0 <= 节点个数 <= 5000

    解答 By 海轰

    提交代码(双指针)

    ListNode* reverseList(ListNode* head) { ListNode* cur=NULL; ListNode* pre=head; while(pre){ ListNode* temp=pre->next; pre->next=cur; cur=pre; pre=temp; } return cur; }

    运行结果 提交代码(递归)

    ListNode* reverseList(ListNode* head) { if(head==NULL || head->next==NULL){ return head; } ListNode* res=reverseList(head->next); head->next->next=head; head->next=NULL; return res; }

    运行结果

    递归详解图(以1–>2–>3–>null 为例) 提交代码(优秀!)

    ListNode* reverseList(ListNode* head) { if(!head) return head; ListNode* cur=head; while(head->next){ ListNode* temp=head->next->next; head->next->next=cur; cur=head->next; head->next=temp; } return cur; }

    运行结果

    题目来源

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof

    海轰Pro 认证博客专家 C/C++ 微信小程序 微信小程序:「海轰Pro」微信公众号:「海轰Pro」知乎:「海轰Pro」微博:「海轰Pro」
    Processed: 0.011, SQL: 9