I'm trying to create a sorted linked list in C with the following code but I am getting a segmentation fault before any of my input is printed. I believe it is because I'm checking ((*link)->value < val)
in my while loop, but at the beginning, it is NULL
. I also tried adding a conditional for if there are no elements in the list but that didn't work. How could I check to see if the value to add is smaller without getting seg. fault?
struct NodeTag {
int value;
struct NodeTag *next;
};
typedef struct NodeTag Node;
typedef struct {
Node *head;
int length;
} List;
void insertSorted(List *list, int val) {
Node **link = &(list->head);
while (*link != NULL || (*link)->value < val) {
//move node to correct place in list
link = &((*link)->next);
}
//create new node
Node *n = (Node *)malloc(sizeof(Node));
n->value = val;
//set next to null
n->next = NULL;
//insert new node
*link = n;
}
Here is printList:
void printList(List *list) {
printf("%d elements :", list->length);
for (Node *n = list->head; n; n = n->next)
printf( " %d", n->value);
printf( "\n" );
}
Input: 72 19 47 31 8 36 12 88 15 75 51 29
Expected output: 8 12 15 19 29 31 36 47 51 72 75 88