35. 反转链表 - AcWing题库
//头插法反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//空链表处理
if (head == nullptr)
return head;
//创建虚拟头结点
auto dummy = new ListNode(-1);
//将head头插如dummy内
for (auto p = head, t = head->next; p != nullptr; p = t)
{
t = p->next;
p->next = dummy->next;
dummy->next = p;
}
return dummy->next;
}
};
思路二
//迭代法反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
auto ans = (ListNode*)nullptr;
auto p = head;
while (p)
{
auto t = p->next;
//ans连到p后面
p->next = ans;
//更新ans
ans = p;
//p往下走
p = t;
}
return ans;
}
};
思路三
//递归法反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//空链表处理以及递归终点
if (head == nullptr || head->next == nullptr)
return head;
//将自head->next以后的链表反转
//ans为原链表的最后一个节点,也是新的头结点
auto ans = reverseList(head->next);
//head->next是ans的末端节点
//将head连在head->next后
//也即连在ans末端
head->next->next = head;
//head是新的链表末端
head->next = nullptr;
return ans;
}
};