题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
// 空间复杂度要求为O(1),则不能开辟空间
if (pHead == nullptr) {
return nullptr;
}
ListNode* pTemp = nullptr; // 用于记录剩余链表的头节点,防止断掉找不到头
ListNode* pPre = nullptr; // 用于记录前置节点
while (pHead) {
pTemp = pHead->next;
pHead->next = pPre;
pPre = pHead;
pHead = pTemp;
}
return pPre;
}
};
2023 剑指-链表 文章被收录于专栏
2023 剑指-链表