题目描述
输入一个链表,反转链表后,输出新链表的表头。
题目地址
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;
}
};