#include<iostream>
#include<list>
using namespace std;
class Soluation {
public:
struct ListNode {
int val;
ListNode* next;
ListNode():val(0), next(nullptr){}
ListNode(int val) : val(val), next(nullptr) {}
ListNode(int val, ListNode* next): val(val), next(next){}
};
// 双指针法
ListNode* reverseList1(ListNode* head) {
ListNode* cur = head;
ListNode* pre = NULL;
ListNode* tmp;
while (cur) {
// 翻转
tmp = cur->next;
cur->next = pre;
// 更新
pre = cur;
cur = tmp;
}
return pre;
}
// 递归法
ListNode* reverseList2(ListNode* head) {
return reverse(NULL, head);
}
ListNode* reverse(ListNode* pre, ListNode* cur) {
if (cur == NULL) return pre;
ListNode* tmp = cur->next;
cur->next = pre;
// 下面行可以换成 return reverse(cur,tmp);
pre = cur;
cur = tmp;
return reverse(pre, cur);
}
};
链表-反转链表-双指针、递归
于 2023-09-16 21:53:04 首次发布