题目链接: 206. 反转链表 - 力扣(LeetCode)
题目描述
解题思路
- 定义三个节点,tmp、pre、cur
- tmp用来交换前面一个节点和当前节点
- 设置前面一个节点先为null,当前节点指向head
- 遍历当前节点。每次遍历的时候交换当前节点和前节点。并将当前节点保存的下一个节点的地址放到tmp里面去
- 最后将tmp还给当前节点
- 返回pre节点
代码实现
/**
* 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* temp; // 保存cur的下一个节点
ListNode* cur = head;
ListNode* pre = NULL;
while(cur) {
temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next
cur->next = pre; // 翻转操作
// 更新pre 和 cur指针
pre = cur;
cur = temp;
}
return pre;
}
};