这是我的代码,用于删除参数中传递的值的所有节点。
typedef struct nodetype
{
int data;
struct nodetype * next;
} node;
typedef node * list;
void Linklist::deleteNode(list * head, int value)
{
list current = *head;
list previous = *head;
while(current != NULL)
{
if(current->data != value)
{
previous = current;
current = current->next;
}
else if (current->data == value)
{
previous->next = current->next;
delete current;
current = previous->next;
}
}
}
但是这里如果链表中的所有元素都是 2,那么它应该删除链表中的所有元素,最后 head 也应该变为 NULL 这样如果我传递这个 head 来计算列表中的节点数它应该说是列表清空等类似的操作。
根据我当前的实现,对于上述情况,head 不会变为 NULL。
请建议修改,如果链接列表中所有节点的函数参数都具有相同的值,则 head 应变为 NULL。
最佳答案
我现在修改了我的代码和它的工作文件
void Linklist::deleteNode(list *head, int value)
{
list * current = head;
list * previous = head;
bool flag = false;
while(*current != NULL)
{
if((*current)->data != value)
{
*previous = *current;
*current = (*current)->next;
}
else if ((*current)->data == value)
{
flag = true;
(*previous)->next = (*current)->next;
delete *current;
*current = (*previous)->next;
}
}
if(!flag)
cout<<"Element not found in the linklist\n";
cout<<"Count is "<<Linklist::count(*head)<<endl;
}
关于c++ - 删除链表中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198129/