递归和迭代两种方法,我觉得就链表而言迭代更有训练价值
这个递归就挺抽象的,给人一种不知道归到哪去的感觉。
我的理解是这样的,函数返回的已经反序的后半段列表(反转是从后往前),每次要处理的就算自己和已经反转完成的后半段,调整后要把head->next记为Nullptr,防止环的出现
#include<iostream>
using namespace std;
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)return nullptr;
ListNode* ans = new ListNode(head->val);
ListNode* p = head;
while (p->next != nullptr) {
ListNode* q = new ListNode(p->next->val);
q->next = ans;
ans = q;
p = p->next;
}
return ans;
}
};
//题解的迭代
class Solution1 {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
//题解的递归
class Solution2 {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
void print(ListNode* head)//输出结果链表
{
ListNode* p;
p = head;
while (p != NULL)
{
cout << p->val << " ";
p = p->next;
}
}
int main() {
Solution test;
ListNode* a = new ListNode(1);
a->next = new ListNode(2);
a->next->next = new ListNode(6);
a->next->next->next = new ListNode(6);
a->next->next->next->next = new ListNode(4);
a->next->next->next->next->next = new ListNode(5);
a->next->next->next->next->next->next = new ListNode(6);
ListNode* ans = test.reverseList(a);
print(ans);
}