链表删除注意点
- 链表作为函数出口返回
- 删除首节点
- 删除中间节点注意保护
代码实现
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(nullptr){}
};
void deleteListNode(ListNode **pHead, int value){
ListNode *pToBeDelete = nullptr;
if(pHead == NULL || *pHead == NULL){
return ;
}
//想要删除的节点为第一个节点
if((*pHead)->val == value){
pToBeDelete = *pHead;
*pHead = (*pHead)->next;
}else{
ListNode *pNode = *pHead;
while (pNode->next != nullptr && pNode->next->val != value) {
pNode = pNode->next;
if(pNode->next != nullptr && pNode->next->val == value){
pToBeDelete = pNode->next;
pNode->next = pNode->next->next;
}
}
}
if(pToBeDelete != nullptr){
delete pToBeDelete;
pToBeDelete = nullptr;
}
}
网友评论