函数来检查 C 链表中是否存在字符串



我正在为课堂编写一个程序,我的老师要求我们在添加之前检查列表中是否已存在名称。我为此编写的代码似乎无法正常工作。

    void doAdd (waitListPtr hd)
{
 /* get group size from input */
int size = getPosInt();
if (size < 1)
{
printf ("Error: Add command requires an integer value of at least 1n");
printf ("Add command is of form: a <size> <name>n");
printf ("  where: <size> is the size of the group making the reservationn");
printf ("         <name> is the name of the group making the reservationn");
return;
}
/* get group name from input */
char *name = getName();
 if (NULL == name)
{
printf ("Error: Add command requires a name to be givenn");
printf ("Add command is of form: a <size> <name>n");
printf ("  where: <size> is the size of the group making the reservationn");
printf ("         <name> is the name of the group making the reservationn");
return;
}
    if(doesNameExist(hd, name) == TRUE){
        printf("nERROR: Name already on list");
    }else{
    printf ("Adding group "%s" of size %dn", name, size);
    addToList(&hd, size, name);
    hd->groupStatus = PRESENT;
    }
}

它永远不会给出错误,并且始终只是将名称添加到列表中。

下面是 doesNameExists 函数:

int doesNameExist(waitListPtr hd, char* name){
waitListPtr ptr = hd;
while(ptr != NULL){
    if(strcmp(ptr->groupName, name)== 0){
        return TRUE;
    }
    else{
        ptr=ptr->next;
    }
}
return FALSE;

}

这是我的链表结构的声明

typedef struct waitListStruct
{
char      groupName[30];
int       groupSize;
int       groupStatus;
struct    waitListStruct*  next;
} waitList;
typedef waitList* waitListPtr;

这是将新节点添加到列表的函数

void addToList(waitListPtr* hd, int size, char* name){
waitListPtr ptr = (waitListPtr) malloc (sizeof(waitList));
strcpy(ptr->groupName, name);
ptr->groupSize = size;
ptr->next = *hd;
*hd = ptr;
}

这是 main 中调用函数的部分

int main (int argc, char **argv)
{
 waitListPtr head = NULL;

 while ((ch = getNextNWSChar ()) != EOF)
 {
if('a' == ch)
  {
   doAdd(head);
 }
 }
 }

谁能告诉我我做错了什么?

if(strcmp(ptr->groupName, &name)== 0){

是不对的。我很惊讶您的编译器没有将其标记为错误。

它需要:

if(strcmp(ptr->groupName, name)== 0){
                    //   ^^ Drop the &

改进建议

该函数中的while循环可以简化为:

while(ptr != NULL)
{
   if (strcmp(ptr->groupName, name) == 0)
      return TRUE;
   ptr=ptr->next;
}
while(ptr != NULL){
    // Remove & from the name , Check man page of strcmp 
    if(strcmp(ptr->groupName, name)== 0){
        return TRUE;
        // Remove this line as it is unreachable as you are returning
        break;
    }

更改加法逻辑

void addToList(waitListPtr* hd, int size, char* name){
waitListPtr ptr = (waitListPtr) malloc (sizeof(waitList));
strcpy(ptr->groupName, name);
ptr->groupSize = size;
if (*hd == NULL)
{
   ptr->next = NULL;
} else {
    ptr->next = *hd;
}
    *hd = ptr;
}

希望解决问题 #peace

相关内容

  • 没有找到相关文章

最新更新