题解 | #反转链表#
反转链表
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) {
ListNode* tmp1;
ListNode* tmp2;
if(pHead == nullptr)
return nullptr;
tmp1 = pHead->next;
pHead->next = nullptr;
while(tmp1 != nullptr){
tmp2 = tmp1->next;
tmp1->next = pHead;
pHead = tmp1;
tmp1 = tmp2;
}
return pHead;
}
};
设置两个临时指针用于保存当前要处理的节点和该节点的下一个节点,要主语输入范围包含了0个节点因此需要判空
查看14道真题和解析