I am a beginner in Data structures and I am learning linked list now . I encountered a program about sorted insert where I had an add() function to add the nodes in the sorted order
/*Linked List program to add ascending order sorted nodes in
the list */
#include <stdio.h>
#include <stdlib.h>
enter code here
struct node {
int data ;
struct node link;
};
void add(struct node **q,int num){
struct node *r,*temp = *q;
r = malloc(sizeof(struct node )); //Data Allocated
r->data = num;
if(*q==NULL ||(*q)->data >num){
*q = r;
(*q)->link = temp;
}else{
while(temp !=NULL){
if(temp->data <=num &&(temp->link->data >num
||temp->link==NULL)){
r->link = temp->link;
temp->link=r;
return;
}
temp = temp->link;
}
}
}
void main(){
struct node *p;
p = NULL;
}
I have expected to add the nodes in sorted ascending order but when I input data then error is shown.I am Using Code Blocks to run the program in C
I think it has to do something with the end condition temp->link == null but I am unable to figure out exact condition for that part of code .Please Help !
temp !=NULLbut you are accessingtemp->link.temp->linkcan beNULLin which case you have undefined behaviour.struct node *link;