题目描述:
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2] 输出:[2,1]
示例 3:
输入:head = [] 输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
算法:
Step1:定义temp、prev、cur三个指针,初始化:temp=nullptr,prev=head,cur=head->next(即目前temp是空指针,prev指向头结点,cur指向第一个节点)。
Step2:prev指向temp,temp放到prev,prev放到cur,cur继续遍历,当cur指向空时停止遍历,而当prev指向空时结束循环。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr) { return nullptr; }//判断该链表是否为空链表
ListNode* temp = nullptr;
ListNode* prev = head;
ListNode* cur = head->next;
while (prev) {
prev->next = temp;//循环的条件是prev不为空时,则将该结点指向前面的结点,实现翻转
temp = prev;
prev = cur;//temp、prev往后移动
if (cur)
cur = cur->next;//当cur不为空时,cur也往后移动,遍历链表
}
return temp;
}
};
以下是一个测试代码:
#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) {
if (head == nullptr) { return nullptr; }//判断该链表是否为空链表
ListNode* temp = nullptr;
ListNode* prev = head;
ListNode* cur = head->next;
while (prev) {
prev->next = temp;//循环的条件是prev不为空时,则将该结点指向前面的结点,实现翻转
temp = prev;
prev = cur;//temp、prev往后移动
if (cur)
cur = cur->next;//当cur不为空时,cur也往后移动,遍历链表
}
return temp;
}
};
int main() {
// 定义链表的头节点和当前节点
ListNode* head = nullptr;
ListNode* current = nullptr;
// 定义链表要包含的节点数量
int n = 5;
// 使用循环创建链表节点
for (int i = 1; i <= n; ++i) {
// 创建新节点
ListNode* newNode = new ListNode(i);
// 如果链表为空,新节点就是头节点
if (head == nullptr) {
head = newNode;
current = newNode;
}
else {
// 否则,将新节点添加到链表的末尾
current->next = newNode;
current = newNode;
}
}
// 打印链表
cout << "反转链表前:" << endl;
current = head;
while (current != nullptr) {
cout << current->val << " ";
current = current->next;
}
cout << endl;
// 反转链表
Solution solution;
head = solution.reverseList(head); // 更新head指针以指向反转后的链表
// 打印反转后的链表
cout << "反转链表后:" << endl;
current = head;
while (current != nullptr) {
cout << current->val << " ";
current = current->next;
}
cout << endl;
// 释放链表内存
current = head;
while (current != nullptr) {
ListNode* toDelete = current;
current = current->next;
delete toDelete;
}
return 0;
}
运行结果如图: