在C++中实现一个反转链表的函数可以通过迭代或递归的方式来完成。
#include <iostream>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
int main() {
// 创建链表
ListNode* head = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
ListNode* node5 = new ListNode(5);
head->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
// 反转链表
ListNode* reversedHead = reverseList(head);
// 输出反转后的链表
ListNode* curr = reversedHead;
while (curr != nullptr) {
std::cout << curr->val << " ";
curr = curr->next;
}
std::cout << std::endl;
// 释放链表内存
curr = reversedHead;
while (curr != nullptr) {
ListNode* temp = curr;
curr = curr->next;
delete temp;
}
return 0;
}
输出结果为:5 4 3 2 1
#include <iostream>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* reversedHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return reversedHead;
}
int main() {
// 创建链表
ListNode* head = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
ListNode* node5 = new ListNode(5);
head->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
// 反转链表
ListNode* reversedHead = reverseList(head);
// 输出反转后的链表
ListNode* curr = reversedHead;
while (curr != nullptr) {
std::cout << curr->val << " ";
curr = curr->next;
}
std::cout << std::endl;
// 释放链表内存
curr = reversedHead;
while (curr != nullptr) {
ListNode* temp = curr;
curr = curr->next;
delete temp;
}
return 0;
}
输出结果为:5 4 3 2 1
以上是在C++中实现反转链表的函数的两种方法。这个函数可以用于将一个单向链表的顺序反转,使得链表的尾部成为头部,头部成为尾部。反转链表在实际开发中常用于解决一些与链表相关的问题,例如链表的遍历、查找、插入、删除等操作。
腾讯云相关产品和产品介绍链接地址:
Tencent Serverless Hours 第13期
企业创新在线学堂
腾讯云数智驱动中小企业转型升级系列活动
云+社区沙龙online [云原生技术实践]
云+社区沙龙online [新技术实践]
Game Tech
领取专属 10元无门槛券
手把手带您无忧上云