c - 这些删除列表项算法之间的区别
问题描述
我为从单链表中删除项目/项目编写了三个算法。1号工作正常。2号也可以正常工作。3号不起作用,我知道。但是为什么数字 3 不正确,数字 2 和双指针有什么区别?
1号:
struct nodo * delete1(struct nodo * top, int data) {
struct nodo *current, *temp;
if(top->valore == data ) {
current = top->next;
free(top);
top = current;
}
current = top;
while (current->next)
{
if (current->next->valore == data)
{
temp = current->next->next;
free(current->next);
current->next = temp;
}
else
current = current->next;
}
return top;
}
2号:
void delete2(struct nodo **p, int k) {
while(*p) {
if ((*p)->valore == k)
{
struct nodo * tmp = (*p)->next;
free(*p);
(*p) = tmp;
}
else
{
p = &(*p)->next;
}
}
}
3号:
struct nodo * delete3(struct nodo * top, int k) {
struct nodo * curr = top;
while(curr) {
if(curr->d == k) {
struct nodo * tmp = curr->next;
free(curr);
curr = tmp;
}
else curr = curr->next;
}
return top;
}
解决方案
对于初学者来说,这三个函数具有不同的行为。
在第一个函数中,如果列表的第一个节点的值等于指定值,则仅删除该第一个节点。否则,所有具有指定值的节点都将被删除。
但是在任何情况下,即使您更新了函数,它也可以调用未定义的行为,例如当为空列表调用时或当列表的单个节点被删除时。
在第二个函数中,删除所有值等于指定值的节点(与第一个节点的值是否等于指定值无关)。
第三个函数是完全错误的,因为它改变了局部变量curr
,而不是变量 top 或节点的任何数据成员 next。也就是说,无论指向的节点是否被删除,函数都会返回指针 top 的先前值。
为了使第一个函数的行为类似于第二个函数的行为,应该按以下方式定义。
struct nodo * delete1(struct nodo * top, int data)
{
while ( top && top->valore == data )
{
struct nodo *temp = top->next;
free( top );
top = temp;
}
if ( top )
{
struct nodo *current = top;
while (current->next)
{
if ( current->next->valore == data )
{
struct nodo *temp = current->next->next;
free( current->next );
current->next = temp;
}
else
{
current = current->next;
}
}
}
return top;
}
推荐阅读
- oracle - 在 RMAN 备份期间,关闭即时数据库并面临错误 ORA-12514: TNS:listener?
- amazon-web-services - AWS EKS 集群、DockerHub 和 Traefik,无法从 Internet 访问
- python - 为什么numpy数组nan的max和min是?
- typescript - 我应该如何使用 TypeScript 编译器 API 获得 Common JS 导出?
- python - Kivy 应用程序使用 buildozer 成功构建,但在 android 手机上打开时崩溃
- c# - C# Windows 窗体应用程序热键 - KeyDown 事件不起作用
- swift - macOS:从 CharacterPalette 中获取 Emoji(修订版)
- amazon-cloudformation - 创建 RDS 数据库用户 CloudFormation
- javascript - 随机化脚本中的颜色
- php - 从 mysql 中选择等于 URL 的值