Compare two linked lists !

Comparing two lists means , return true if they are exactly same otherwise return false.

I have done it recursively.

bool compare( struct node *p1, struct node *p2)
{
if( p1==NULL && p2==NULL)
return true;
else if( p1==NULL || p2==NULL)
return false;
else if(p1->data !=p2->data)
return false;
else
compare(p1->link,p2->link) ;
return true;
}

  1. #1 by Jackie on June 21, 2007 - 2:47 pm

    How would you do this for a circularly linked lists?

  2. #2 by encrypt3d on June 21, 2007 - 5:43 pm

    for circular list, the condition for the end of the list will change.

    bool compare(struct node *p1, struct node *p2)

    { if(p1->link == p1 && p2->link ==p2)
    return true;
    else if(p1->link ==p1 || p2->link ==p2)
    return false;
    else
    compare(p1->link,p2->link);
    }

  3. #3 by Tommy on January 19, 2010 - 8:31 pm

    This works only for lists which are sorted. Does not work to compare linked lists which are ordered in any fashion.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.