How to compare two lists chained in C?

0

I'm having trouble with this issue:

-I have to compare two linked lists and return 1 if they are equal or 0 if they are not.

The function is like this and I can not progress:

  struct Node
  {
 int data;
 struct Node *next;
 }





 int CompareLists(Node *headA, Node* headB) 
 { 
  /*se as duas forem vazias*/
   if(headA->next==NULL && headB->next==NULL) 
  { 
   return 1; 
   } 
   if(headA->next==NULL || headB->next==NULL) 
   { 
   return 0; 
   }  
   while(headA->next!=NULL && headB->next!=NULL) 
   { 
   if(headA->data=!headB->data) 
   { 
   return 0; 
   }else{ 
   return 1; 
   } 
   headA=headA->next; 
   headB=headB->next; 

   } 
   }

I think the problem is to go through the list ( headA = headA-> next ), but I do not know how to do it. Can anyone help me?

    
asked by anonymous 11.04.2018 / 01:57

1 answer

1

To compare lists, you have to scroll through the lists until you reach a conclusion. This while will only end when at least one of them reaches NULL (which will be tested in the while):

while(headA->next != NULL && headB->next != NULL){
    ...
    headA = headA->next;
    headB = headB->next;
}

These are the last lines, that is, when headA is in the penultimate structure (ie headA-> next is NULL), the while will not be performed because headA hit the penultimate and headB did not:

while(0 && 1) => while(0)

That is, the iteration has finished. When the iteration ends, the function does not respond, it simply exits because the only outputs the function has are if's

int CompareLists(Node *headA, Node* headB) 
{ 
   /*se as duas forem vazias*/
   if(headA->next==NULL && headB->next==NULL) 
   { 
       return 1; 
   } 
   if(headA->next==NULL || headB->next==NULL) 
   { 
       return 0; 
   }  
   while(headA->next!=NULL && headB->next!=NULL) 
   { 
       if(headA->data=!headB->data) 
       { 
           return 0; 
       }else{ 
           return 1; 
       } 
       headA=headA->next; 
       headB=headB->next; 

   } 
}
    
11.04.2018 / 02:16