I am working on a problem that gives two sorted linked lists and asks to find the intersection of two lists and create a new list with the elements as the common elements.
I am attaching my code.
#include<stdio.h>
#include<stdlib.h>
struct node{
int val;
struct node *next;
};
void getval(struct node *p)
{
scanf("%d",&p->val);
p->next=NULL;
}
void createlist(struct node **p , int n)
{
int i=0;
struct node *str =NULL;
for( i=0;i<n;i++)
{
if(*p==NULL)
{
*p = (struct node*)malloc(sizeof(struct node));
str = (struct node*)malloc(sizeof(struct node));
*p = str;
getval(*p);
}
else
{
str->next = (struct node*)malloc(sizeof(struct node));
getval(str->next);
str=str->next;
}
if(i==n-1)
{
str=NULL;
}
}
}
void intersectlist(struct node *p1 , struct node *p2 )
{
int i=0,j=0;
struct node *head3=NULL;
struct node *str= NULL;
struct node *p3= NULL;
for(i=0;p1!=NULL;i++)
{
p3=p2;
for(j=0;p3!=NULL;j++)
{
if(p1->val == p3->val)
{
if(head3==NULL)
{
head3 = (struct node*)malloc(sizeof(struct node));
str = (struct node*)malloc(sizeof(struct node));
head3 = str;
head3->val=p3->val;
}
else
{
str->next = (struct node*)malloc(sizeof(struct node));
str->val = p3->val;
str=str->next;
}
break;
}
p3=p3->next;
}
p1= p1->next;
}
str = NULL;
struct node *p = NULL;
p=head3;
while(p!=NULL)
{
printf("%d ",p->val);
p=p->next;
}
}
int main(){
struct node *head1=NULL;
struct node *head2=NULL;
int i,a=0,n1=0,n2=0;
printf("enter the size of list 1 :");
scanf("%d",&n1);
printf("enter the elements of list 1 :");
createlist(&head1,n1);
printf("enter the size of list 2 :");
scanf("%d",&n2);
printf("enter the elements of list 2 : ");
createlist(&head2,n2);
intersectlist(head1 , head2);
return 0;
}
Here in the function intersectlist, even though p1( which is head1) is not null, the function doesn't enter the loop. It simply exits the loop and jumps directly to the line (str=NULL). Why is this happening