我正在编写一个从链表中删除特定节点的函数。该函数适用于大多数情况,但在要删除的节点是头节点或链表中的唯一节点时不起作用。在这种情况发生的时候,我尝试将电流设置为等于NULL,但这会产生分段错误,我的逻辑错在哪里?
void deleteNodeAfter(Node *head, Node *delete) {
bool remove = false;
Node *current = head;
Node *delNode = delete;
if (current->songName == delNode->songName){
current= NULL;
remove = true;
}
while (!remove) {
if (current->link->songName == delNode->songName) {
current->link = delNode->link;
remove = true;
// free(delNode);
} else {
current = current->link;
}
}
}
答案 0 :(得分:0)
如果删除第一个,则需要更新originla列表指针:
void deleteNodeAfter(Node **head, Node *delete) {
Node *current = *head;
if( first ) {
*head = (*head)->next;
free(current);
}
}
您需要将pointer to pointer
传递给第一个而不是pointer
。使用:
Node *head;
Node *after;
...
deleteNodeAfter( &head, after );
答案 1 :(得分:0)
void deleteNodeAfter(Node **head, Node *delete) {
bool remove = false;
Node *current;
while(current=*head;head=&(current->next),current=*head;current)
{
if (current->songName == delNode->songName){
// perhaps the above check should be current==delNode
*head=current->next
free(current)
return;
}
}
}
您需要传入一个指向列表指针的指针,以便删除操作可以更新指向llist的指针。