题目描述
反转一个单链表
思路1-迭代
假设链表为 1 -> 2 -> 3 -> nullptr
反转后为3 -> 2 -> 1 -> nullptr
(1)当遇到1时,将1->nullptr看成一个整体,提出来
(2)当遇到2时,将1->nullptr这个整体放在2后面,形成一个新的整体,也就是2->1->nullptr
(3)当遇到3时,将新整体2->1->nullptr放在3后面,形成一个新的整体,也就是3->2->1->nullptr
(4)返回头指针结束
代码1
/*
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 cur = pHead, newHead = pHead;
while (cur){
auto next = cur->next;
cur->next = newHead;
newHead = cur;
cur = next;
}
pHead->next = nullptr;
return newHead;
}
};
思路2-递归
代码2
/*
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;
ListNode* node = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = nullptr;
return node;
}
};