/**
* 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) {
if (head) {
ListNode* pre = head;
ListNode* cur = pre->next;
head->next = NULL;
while (cur != NULL) {
ListNode* temp = pre;
pre = cur;
cur = cur->next;
pre->next = temp;
}
return pre;
}
return head;
}
};

总结
- 共耗时20分钟
- 逻辑没有问题,就是简单的原地翻转
- 报错的都是空指针问题,需要在最开始判断一次head是否空
该博客介绍了如何使用C++实现单链表的原地翻转,详细解析了翻转过程中的逻辑,特别强调了在翻转前检查头结点是否为空以避免空指针错误。此外,还讨论了翻转操作的时间复杂度和其作为基础数据结构操作的重要性。
2180

被折叠的 条评论
为什么被折叠?



