Can't validate last node of linked list

67 Views Asked by At

I'm trying to make a program where i use linked list to store data of cakes, currently i am making an add cake function. This function will validate a few things. I want to validate so that the input code must not be the same as an existing code in the linked list. Here is the function :

struct cookie
{
    char code[10], name[100];
    int stock, price;
    struct cookie *next;
};

int validateCode(struct cookie *test, char kode[10]){
    int check;
    int flag;
    while(test != NULL){
        check = strcmp(test->code, kode);
        if(check == 0){
            flag = 0;
        }
        else{
            flag = 1;
        }
        test = test->next;
    }
    if(flag == 1){
        printf("%s already exists in the linked list", kode);
    }
    return flag;
}

Here is the output: Output

I tried to change the while condition into something like:

  • test->next != NULL
  • test->code != NULL

and none of it works for me

2

There are 2 best solutions below

3
Pria Cantiq On

ok turns out im stupid lol i found the solution, thank you for the comments, very useful tips

    int validateCode(struct cookie *test, char kode[10]){
        int check;
        int flag;
        while(test != NULL){
            check = strcmp(kode, test->code);
            if(check == 0){
                flag = 1;
                break;
            }
            else{
                flag = 0;
            }
            test = test->next;
        }
        if(flag == 1){
            printf("%s already exists in the linked list", kode);
        }
        return flag;
    }
0
Vlad from Moscow On

If you want to check whether a specified data is already present in the list then the while loop within the function should stop its iterations as soon as the data is found in the list.

Also pay attention to that the standard C string function strcmp returns 0 when two strings are equal each other. So if the function strcmp returns 0 then it means that the data is present in the list.

The function can be declared and defined the following way

int validateCode( const struct cookie *test, const char kode[] )
{
    while ( test != NULL && strcmp( test->code, kode ) != 0 )
    {
        test = test->next;
    }

    return test != NULL;
}

The function returns 1 if the data is present in the list. Otherwise it returns 0.

The both function parameters should be declared with qualifier const because pointed data are not changed within the function. And the function should not output any message. It is the caller of the function that will decide whether to output a message.