Here is my code.
While debugging i found out that a segmentation fault error while the third element 6 is added.
Code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
};
void display(struct node *q) {
while(q != NULL) {
printf("%d ",q -> data);
q = q -> link;
}
}
int count(struct node *q) {
int c = 0;
while(q != NULL) {
c++;
q = q -> link;
}
return c;
}
void add(struct node **q,int num) {
struct node *r,*temp = *q;
r = (struct node *)malloc(sizeof(struct node));
r -> data = num;
if(*q == NULL || num < (*q) -> data) {
*q = r;
r -> link = temp;
}
else {
while(temp != NULL) {
if(num >= temp -> data && (num < temp -> link -> data || temp -> link == NULL)) {
r -> link = temp -> link;
temp -> link = r;
return;
}
temp = temp -> link;
}
}
}
int main() {
struct node *p = NULL;
add(&p,5);
add(&p,1);
add(&p,6);
add(&p,4);
add(&p,7);
display(p);
}
Please help guys