
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr) return nullptr;
//经典两指针
ListNode* pre = nullptr;
ListNode* cur = pHead;
//遍历
while(cur != nullptr){
//临时指针
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
- 时间复杂度:O(n),遍历链表一次,一次循环
- 空间复杂度:O(1),常数级变量,无额外辅助空间使用
461

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



