0
点赞
收藏
分享

微信扫一扫

LeetCode刷题(23)~反转链表【递归未懂!】


题目描述

反转一个单链表。

示例:

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

解答 By 海轰

提交代码

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL) return head;
ListNode* p=head;
ListNode* q=head->next;
p->next=NULL;
ListNode* temp;
while(q)
{
temp=q;
q=q->next;
temp->next=p;
p=temp;
}
return p;

}
};

运行结果

LeetCode刷题(23)~反转链表【递归未懂!】_链表


思路

        简单说来,就是将原链表一个一个再移出,重新添加在另一链表的头部。

解答

  • 递归
  • 迭代

迭代

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* p=NULL;
ListNode* q=head;
while(q)
{
ListNode* temp=q->next;
q->next=p;
p=q;
q=temp;
}
return p;
}
};

LeetCode刷题(23)~反转链表【递归未懂!】_leetcode_02

递归

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* cur=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return cur;
}
};

LeetCode刷题(23)~反转链表【递归未懂!】_递归_03


​​思路详解🙃​​


举报

相关推荐

0 条评论