Showing posts with label c tutorials. Show all posts
Showing posts with label c tutorials. Show all posts

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.

C Code To Find If Two Binary Trees Are Identical

How To Find If Two Binary Trees Are Identical?

If the two trees have same structure and data in corresponding nodes must be equal then the two binary trees are identical.


C Code To Find If Two Binary Trees Are Identical:

#define IDENTICAL 0
#define NOT_IDENTICAL 1

int identical ( struct node* a, struct node* b ) 
{ 
if ( a == NULL && b == NULL )
{
return ( IDENTICAL );
}
else if (a != NULL && b != NULL ) 
{ 
return(  ( a->data == b->data )  && identical ( a->left, b->left ) &&  identical( a->right, b->right ) ); 
} 
else
{
return( NOT_IDENTICAL ); 
}
}

On invoking this recursive function, it will return 0 or 1 based on the two binary trees passed to the function. 

C Program To Find Height/Depth Of Binary Tree [ How To ]

What Is Height/Depth Of A Binary Tree?

 A binary tree of height  h ( > 0 ), has at least h elements and at most (2^h -1) elements in it.


C Program Code To Find Height/Depth Of a Tree:

int binary_tree_height ( mynode *p )
{
  if ( p == NULL )
return ( 0 );

if ( p->left )
h1 = binary_tree_height ( p->left );

if ( p->right )
h2 = binary_tree_height ( p->right );

return ( max ( h1, h2 ) + 1 );
} 


When You invoke this recursive function, it will return height/depth of a binary tree.

Share This