c - 我需要这部分代码的帮助

标签 c linked-list

我的代码提示用户输入用户想要从指针数组中删除的名称,然后在链接列表中搜索并删除该名称。但我的代码正在删除指针数组中的所有名称,除了数组中的最后一个名称。这是我的删除功能。

int delete (studPtr *sPtr, Student myStud)
{

    studPtr previous = NULL;
    studPtr current = NULL;
    studPtr temp = NULL;
    while ((*sPtr)->nextPtr != NULL)
    {
        //previous = *sPtr;

        if ((*sPtr)->name == myStud.name)
        {
            temp = *sPtr;
            (*sPtr) = (*sPtr)->nextPtr;
            current = (*sPtr);
            previous->nextPtr = current;
            free(temp);

        }
        else
        {
            previous = *sPtr;
            (*sPtr) = (*sPtr)->nextPtr;
        }


    }
    return 1;


}

这是我的指针数组

char *studentname[] = { "Abbie", "Oakley", "Sylvia", "Uwe", "Ken", "Aaron", "Fabien",'\0' };

这会调用该函数。

printf("Enter students name: \n");
scanf("%s", Stud.name);
int convert_char = determineIfConvert(Stud.name);
if (convert_char == 1)
{
    convert(Stud.name);
}
int delete_student = delete(&startPtr, Stud);
if (delete_student == 1)
{
    printf("student deleted");
    printList(startPtr);
}
else
{
    printf("student not found\n");
}

最佳答案

数组中的最后一个元素不会被删除,因为 (*sPtr)->nextPtr 在该实例中为 NULL,并且 while 循环被终止并且 if ((*sPtr)->name == myStud.name) 不会被执行。 要解决这个问题,您可以使用 do while 循环。在 do while 循环之前,您需要检查 (*sPtr) 是否为 NULL

关于c - 我需要这部分代码的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36702403/

相关文章:

c - 递增常量变量

c - OpenGL - 绘制正弦曲线的切线和法线

c - 将链表的头与其中的链接交换?

c++ - 神奇分配的链表中的头指针,不应该工作但确实如此

c++ - 简单地重命名 cpp 中的文件,无需在其中写入任何内容

python - 如何强制退出 Python 中的 CLOSE_WAIT 套接字?

无法找到 K&R 练习 4-6 的解决方案

java - 添加到链接列表的末尾

c - 从C中的文件中读取链表

c - 添加到双向链表的头部