Monday, July 22, 2013

C Code To Compare Two Linked Lists

Compare Two Linked Lists:

Here we are comparing two linked lists which have same type of data. If number of nodes and the data held by each node are equal then two linked lists are equal.


C Code To Compare Two Linked Lists:

#define EQUAL 0
#define NOT_EQUAL 1

int comp ( struct node *p, struct node *q )
{
if( !p && !q )
return EQUAL;

if(  ( !p && q )  ||  ( !q && p ) )
return NOT_EQUAL;

return (  ( p->data == q->data )  &&  ( comp ( p->node, q->node ) )  );
}

On invoking this recursive function, it will return 0 ( equal ) or 1 ( not equal ) based on linked lists passed to it.

Share This