//finding the merge
point of two lists
//list1 contains
10,15,30
//list 2 contains
3,6,9,15,30 such that
//15 in both the
lists are stored in same location ie merge point
/*ALGO:
-count the list1
say c1
-count the list2
say c2
-absoulte
difference say d
-traverse the
longer list by d nodes
-then traverse
both the lists simueltaeously
-when two nodes
gets equal in address that is point of merge
*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node
*next;
};
void display(struct
node *head1);
int countNode(struct
node *head1);
int
mergePoint(struct node *head1,struct node *head2,int d);
int main()
{
struct node
*head1=(struct node *)malloc(sizeof(struct node));
head1->data=10;
head1->next=NULL;
struct node
*head2=(struct node *)malloc(sizeof(struct node));
head2->data=3;
head2->next=NULL;
struct node
*newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=6;
head2->next=newnode;
newnode=(struct
node *)malloc(sizeof(struct node));
newnode->data=9;
head2->next->next=newnode;
newnode=(struct
node *)malloc(sizeof(struct node));
newnode->data=15;
head2->next->next->next=newnode;
head1->next=newnode;
printf("head2->next->next->next=newnode=%p\n",head2->next->next->next);
printf("head1->next=%p\n",head1->next);
newnode=(struct
node *)malloc(sizeof(struct node));
newnode->data=30;
head1->next->next=newnode;
//head2->next->next->next->next=newnode;
head1->next->next->next=NULL;
display(head1);
printf("\n");
display(head2);
printf("\n");
int c1,c2,d;
c1=countNode(head1);
printf("\n");
c2=countNode(head2);
printf("\n");
if(c1>c2)
{
d=c1-c2;
printf("d=c1=%d\n",d);
}
else
{
d=c2-c1;
printf("d=c2=%d\n",d);
}
int t=0;
t=mergePoint(head1,head2,d);
printf("Merege
point is at node:%d\n",t);
return 0;
}
//function to
display the nodes
void display(struct
node *h)
{
struct node
*current=h;
while(current!=NULL)
{
printf("%d
",current->data);
current=current->next;
}
}
//function to count
the nodes
int countNode(struct
node *h)
{
int count=0;
struct node
*current=h;
while(current!=NULL)
{
count=count+1;
current=current->next;
}
printf("size
of list1=%d\n",count);
return count;
}
//function to give
the merge point
int
mergePoint(struct node *head1,struct node *head2,int d)
{
int i;
struct node
*current1=head1;
struct node
*current2=head2;
for(i=0;i<d;i++)
{
printf("i=%d,current2->data=%d\n",i,current2->data);
current2=current2->next;
}
while(current1!=NULL && current2!=NULL)
{
printf("while=\n");
if(current1==current2)
{
printf("\n\ncurrent1->data====%d\n\n",current1->data);
return
current1->data;
}
current1=current1->next;
current2=current2->next;
}
}
/*OUTPUT:
head2->next->next->next=newnode=0x9dc7048
head1->next=0x9dc7048
10 15 30
3 6 9 15 30
size of list1=3
size of list1=5
d=c2=2
i=0,current2->data=3
i=1,current2->data=6
while=
while=
current->data====15
Merege point is at
node:15*/
No comments:
Post a Comment