![](https://img-blog.csdnimg.cn/img_convert/343b118a90184a20b51380ad0d964b32.png)
![](https://img-blog.csdnimg.cn/img_convert/8d95f6f246db424ebbeb706437128172.png)
思路
最容易想到的是遍历链表,依次将其反向,即迭代法。
迭代法
![](https://img-blog.csdnimg.cn/img_convert/7f6af4065ee841e190147d6b08222f56.png)
用cur来遍历原链表,再不断更新newhead,newhead从nullptr到1。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* newhead = nullptr;
ListNode* cur = head;
while (cur != nullptr)
{
//tmp用来将指针反向
ListNode* tmp = cur;
cur = cur->next;
tmp->next = newhead;
newhead = tmp;
}
return newhead;
}
};
递归法
递归法跟迭代法的逻辑是一样的,如下面解释
reverse中cur用来遍历链表,cur为空返回newhead
用tmp记录下cur->next,那么cur就成了newhead
class Solution {
public:
ListNode*reverse(ListNode*cur,ListNode*newhead)
{
if(cur==nullptr)
return newhead;
ListNode*tmp = cur->next;
cur->next = newhead;
return reverse(tmp,cur);
}
ListNode* reverseList(ListNode* head) {
return reverse(head,nullptr);
}
};