繁体   English   中英

根据内容从双向链表中删除结构(在C中)

[英]Deleting a structure from a doubly linked list based on its contents (in C)

我的程序是一个基本的C接口,允许用户输入,向前打印,向后打印以及从列表中删除MP3记录。 该列表以C语言形式实现为MP3结构的双向链接列表。

除Delete之外,我所有的功能都可以正常工作。 Delete带有指向列表头节点的指针和一个字符串,表示您要删除哪个艺术家的记录。 在我的主笔录中,我记录了用户输入,并确认它已正确记录。 然后,我将用户输入和主要参考传递到以下函数中,以删除所述MP3记录。 但是,我的程序可以正常构建和执行,但是在调用delete函数时实际上并没有删除任何记录。 任何帮助表示赞赏。

为了清楚起见,我已经查看了堆栈上有关从DLL删除节点的多个问题,但是它们都与持有整数值的简单DLL有关,并且似乎不适用于我的情况。 如果这是一个重复的问题,我深表歉意。如果是的话,请指出我要重复的问题。 再次感谢您的协助。 下面是我的功能

void deleteMP3(struct MP3* head_ref, char* artist)
{
    //Declaring a temp struct to hold the node that needs to be deleted
    struct MP3* temp;

    //Check if the head node contains the artist to be deleted
    if(head_ref->artist == artist)
    {
        //Set temp to the current head ref so it can be deleted
        temp = head_ref;

        //Set head_ref to the next node in the list
        head_ref = head_ref->next;

        //Free the memory associated with the MP3 to be deleted
        free(temp->artist);
        free(temp->title);
        free(temp->date);
        free(temp);
    }

    //Traverse the list checking each MP3's artist field
    while(head_ref != NULL)
    {
        //Check the artist of the current MP3 against the input. Delete it if it needs to be deleted
        if(head_ref->artist == artist)
        {
            //Set temp to the current MP3
            temp = head_ref;

            //Check if the MP3 is the last MP3. If not, change the field of the next node in the list
            if(head_ref->next != NULL)
            {
                //Sets the previous field of the next node in the list to the previous field of the node to be deleted
                head_ref->next->prev = head_ref->prev;
            }

            //Change the next pointer of the previous MP3 in the list to the MP3 following the one to be deleted
            head_ref->prev->next = head_ref->next;

            //Free the memory           
            free(temp->artist);
            free(temp->title);
            free(temp->date);
            free(temp);
        }

        //Traverse forward
        head_ref = head_ref->next;
    }
}

代码中有一些问题,但以下两个是最关键的问题:

1.)使用strcmp比较字符串。 head_ref->artist == artist比较指针,而不是内容,并且通常不太可能传递DLL元素指向的指针。

2.)如果头部被删除,则需要将“新”头部传递回deleteMP3的调用方; 否则,传递给deleteMP3的变量仍将保留指向(已删除)节点的指针。 因此将void deleteMP3(struct MP3* head_ref, char* artist)更改为struct MP3 *deleteMP3(struct MP3* head_ref, char* artist)并返回DLL的实际头(无论是否更改)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM