题目链接
思路
定义两个指针,pre指针初始化为null,cur初始化为首元节点。由cur指向pre指针,再不断同时遍历链表,就能实现链表反转。但是如果直接将cur指向pre以后,原本cur的下一个节点就会断开,所以需要用临时指针保存。
代码
/**
* Definition for singly-linked list.
* 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* cur = head;
ListNode* pre = nullptr;
ListNode* tmp;
while (cur)
{
tmp = cur -> next; //保存临时指针
cur -> next = pre; //反转
pre = cur; //遍历
cur = tmp;
}
return pre;
}
};
易错点
- 需要临时保存下一个指针
- pre和cur的初始化
- 需要判断什么时候结束遍历,可以手画出示意图
- 特殊情况处理,比如空链表等