lundi 23 décembre 2019

Compare two linked lists in C

I am a beginner in C and can´t find the problem in my code. Maybe someone has a solution or an advise. The programm should compare two linked lists. If both are equal, the programm should return true and a text ( "lists are equal" ). If list1 is shorter, it should return false and "list 1 is shorter than list2. Same with list1 is longer ( false and "list1 is longer...").

Here is my code. The compiler error is "control reaches end of non-void function". I understand the error but I dont know what to change anymore. Tried many things.

bool compare_list(Node* list1, Node* list2) {
if ( list1 != NULL && list2 != NULL ) {
        while ( list1 != NULL && list2 != NULL ) {
            if ( list1->value == list2->value && list1->next == NULL && list2->next == NULL ) {
                printf("The lists are equal.\n");           
                return true;                
            } else if ( list1->next == NULL && list2->next != NULL ) {
                printf("list1 is shorter than list2.\n");
                return false;
            } else if ( list1->next != NULL && list2->next == NULL ) {
                printf("list1 is longer than list2.\n");
                return false;
            } else {
                printf("The values differ");
                return false;

            }           
            list1 = list1->next;
            list2 = list2->next;
        }       
    } else {
            printf("The lists are equal.\n");           
            return true;
    }

I changed the code a couple of times, so maybe it is completly wrong now. The main problem is still the "control reaches end of non-void function" error. If you find other errors which are not the reason this error occurs feel free to mention it.

Thank you for your help

Aucun commentaire:

Enregistrer un commentaire