给你单链表的头节点head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
- 代码如下:
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution
{
public:
ListNode* reverseList(ListNode* head)
{
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr)
{
//保存当前的下一个节点
ListNode* next = curr->next;
// 指向前驱节点
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
void printList(ListNode* head)
{
ListNode* curr = head;
while (curr)
{
std::cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
int main()
{
// 创建链表 1 -> 2 -> 3 -> 4 -> 5
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
// 打印原链表
std::cout << "Original list: ";
printList(head);
// 创建 Solution 对象并反转链表
Solution solution;
ListNode* reversedHead = solution.reverseList(head);
// 打印反转后的链表
std::cout << "Reversed list: ";
printList(reversedHead);
return 0;
}