题目描述
输入一个链表,反转链表后,输出新链表的表头。
题目地址
Code - 迭代
class Solution {
public:
ListNode * ReverseList(ListNode* head) {
if (pHead == nullptr)
return nullptr;
ListNode* cur = pHead; // 当前节点
ListNode* pre = nullptr; // 前一个节点
ListNode* nxt = cur->next; // 下一个节点
cur->next = nullptr; // 断开当前节点及下一个节点(容易忽略的一步)
while (nxt != nullptr) {
pre = cur; // 把前一个节点指向当前节点
cur = nxt; // 当前节点向后移动
nxt = nxt->next; // 下一个节点向后移动
cur->next = pre; // 当前节点的下一个节点指向前一个节点
}
return cur;
}
};

Code - 递归
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==nullptr||pHead->next==nullptr)
return pHead;
auto nxt=pHead->next;
pHead->next=nullptr;
auto new_head=ReverseList(nxt);
nxt->next=pHead;
return new_head;
}
};

本文详细介绍了两种链表反转的方法:迭代法和递归法。通过具体的代码实现,展示了如何将链表的节点顺序进行反转,并返回新的表头。适用于初学者理解和掌握链表的基本操作。
6万+

被折叠的 条评论
为什么被折叠?



