i'm supposed to create a linked list for the intersection of 2 linked lists. the code i wrote for that shows an extra element -> '0' at the end of the intersection list.
struct ll{
int num;
struct ll *y;
};
typedef struct ll node;
void create(node *list){
char c;
printf("input: ");
scanf("%d", &list -> num);
printf("continue?(y/n)\t");
getchar(); c = getchar();
if(c == 'y'){
list -> y = (node *)malloc(sizeof(node));
create(list -> y); }
else list -> y = NULL;
}
void print(node *list){
if(list -> y != NULL){
printf("%d ->", list -> num);
if(list -> y -> y == NULL) printf("%d", list -> y -> num);
print(list -> y);
}
return;
}
int pres(node *list, int key){
if(list -> num == key) return 1;
else{
if(list -> y == NULL) return 0;
else pres(list -> y, key);
}
}
int count(node *list){
if(list -> y == NULL) return 1;
else return(1+count(list -> y));
}
gin(node *head1, node *head2, node *inter){
node *x = head2, *z = inter;
int n2, i;
n2 = count(head2);
for(i = 0; i<n2; i++){
if(pres(head1, head2 -> num)){
(inter -> num) = (head2 -> num);
inter -> y = (node *)malloc(sizeof(node));
inter = inter -> y; }
inter -> y = NULL;
head2 = head2 -> y;
}
head2 = x; inter = z;
}
main(){
node *head1, *head2, *inter;
head1 = (node *)malloc(sizeof(node));
head2 = (node *)malloc(sizeof(node));
inter = (node *)malloc(sizeof(node));
printf("enter list 1 elements:\n");
create(head1);
printf("\nenter list 2 elements:\n");
create(head2);
printf("\nlist1:\t");
print(head1);
printf("\nlist2:\t");
print(head2);
printf("\nintersection:\t");
gin(head1, head2, inter);
print(inter);
printf("\nno. of items in intersection list = %d\n", count(inter));
}
input
enter list 1 elements:
input: 20
continue?(y/n) y
input: 30
continue?(y/n) y
input: 40
continue?(y/n) y
input: 60
continue?(y/n) n
enter list 2 elements:
input: 10
continue?(y/n) y
input: 30
continue?(y/n) y
input: 50
continue?(y/n) y
input: 60
continue?(y/n) n
output
list1: 20 ->30 ->40 ->60
list2: 10 ->30 ->50 ->60
intersection: 30 ->60 ->0
problem at this point
no. of items in intersection list = 3