题目:
(206)反转链表
方法一:双指针法
自己版本:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode * cur = head->next; //有问题,具体看标准版本,只能初始化为cur = head;
ListNode * left = head;
ListNode * right = left->next->next;
left->next = nullptr;
int length = head.size(); //不能这么写
while(length--){
cur->next = left;
left = cur;
cur = right;
right = right->next;
}
}
};
标准版本:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* temp; // 保存cur的下一个节点
ListNode* cur = head;
ListNode* pre = NULL;
while(cur) {
temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next
cur->next = pre; // 翻转操作
// 更新pre 和 cur指针
pre = cur;
cur = temp;
}
return pre;
}
};
方法二:递归方法
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur){
if(cur == NULL) return pre; //递归结束的条件
ListNode* temp = cur->next;
cur->next = pre;
// 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
// pre = cur;
// cur = temp;
return reverse(cur,temp); //利用函数传参的形式更新参数值
}
ListNode* reverseList(ListNode* head) {
// 和双指针法初始化是一样的逻辑
// ListNode* cur = head;
// ListNode* pre = NULL;
return reverse(NULL, head);
}
};