首页 > 解决方案 > 这些删除列表项算法之间的区别

问题描述

我为从单链表中删除项目/项目编写了三个算法。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;
}

标签: clinked-listsingly-linked-listfunction-definition

解决方案


对于初学者来说,这三个函数具有不同的行为。

在第一个函数中,如果列表的第一个节点的值等于指定值,则仅删除该第一个节点。否则,所有具有指定值的节点都将被删除。

但是在任何情况下,即使您更新了函数,它也可以调用未定义的行为,例如当为空列表调用时或当列表的单个节点被删除时。

在第二个函数中,删除所有值等于指定值的节点(与第一个节点的值是否等于指定值无关)。

第三个函数是完全错误的,因为它改变了局部变量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;
}

推荐阅读