Leetcode206
1.问题描述

2.解决方案
解法一:双指针法
 
记住代码的三步走,就可以了 1.保存cur的下一个节点 2.反转操作 3.更新操作
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre= nullptr;
ListNode* cur=head;
while(cur!= nullptr){
ListNode* temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
};
解法二:递归法
可以看到,其实和解法一思路一摸一样的,也是记住代码的三步走 1.保存cur的下一个节点 2.反转操作 3.更新操作(递归调用)
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur){
if(cur==nullptr) return pre;
ListNode* temp=cur->next;
cur->next=pre;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head) {
ListNode* pre= nullptr;
ListNode* cur=head;
return reverse(pre,cur);
}
};
|