题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
C++
递归法
/**
* 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 {
/*递归法
停止条件:head的后继为空
返回什么: 已经翻转好的链表的头指针
本级递归干什么:记录当前指针,将递归返回的指针指向当前指针
*/
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr)
return head;
ListNode* thisnext=reverseList(head->next);
if(!thisnext)
return head;
ListNode * res=thisnext;
while(thisnext->next)
{
thisnext=thisnext->next;
}
thisnext->next=head;
head->next=nullptr;
return res;
}
};
迭代法:
/**
* 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==nullptr|| head->next==nullptr)
return head;
ListNode * pre=nullptr;
ListNode * cur=head;
ListNode * next=head->next;
while(next){
cur->next=pre;
pre=cur;
cur=next;
next=next->next;
}
cur->next=pre;
return cur;
}
};