用于检查C链表中是否存在字符串的函数

时间:2015-10-19 04:26:51

标签: c function linked-list strcmp

我正在为课程编写程序,我的教师要求我们在添加之前检查列表中是否已存在名称。我写的代码似乎没有正常工作。

    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 1\n");
printf ("Add command is of form: a <size> <name>\n");
printf ("  where: <size> is the size of the group making the reservation\n");
printf ("         <name> is the name of the group making the reservation\n");
return;
}

/* get group name from input */
char *name = getName();
 if (NULL == name)
{
printf ("Error: Add command requires a name to be given\n");
printf ("Add command is of form: a <size> <name>\n");
printf ("  where: <size> is the size of the group making the reservation\n");
printf ("         <name> is the name of the group making the reservation\n");
return;
}
    if(doesNameExist(hd, name) == TRUE){
        printf("\nERROR: Name already on list");
    }else{
    printf ("Adding group \"%s\" of size %d\n", name, size);
    addToList(&hd, size, name);
    hd->groupStatus = PRESENT;
    }
}

它永远不会出错,只是将名称添加到列表中。

这是doesNameExist函数:

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;

}

这是函数调用的主要部分

int main (int argc, char **argv)
{

 waitListPtr head = NULL;


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

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

2 个答案:

答案 0 :(得分:2)

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;
}

答案 1 :(得分:0)

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