This is my code (working on a linked list):
typedef struct node {
int data;
struct node_t* next;
} node_t;
typedef struct list{
node_t* head;
} list_t;
node_t* create_node(void){
node_t* tmp = malloc(sizeof(node_t));
if (tmp == NULL){
fprintf(stderr, "Error while allocating memory for node\n");
exit(EXIT_FAILURE);
}
return tmp;
}
void list_insert(list_t* list, node_t* node, int data){
if (node == NULL){
node_t* new = create_node();
new->next = list->head;
list->head = new;
new->data = data;
}
else{
node_t* current = list->head;
while(current != node){
current = current->next;
}
node_t* new = create_node();
new->next = current->next;
current->next = new;
new->data = data;
}
}
I do get some warnings in list_insert function, but I cannot figure out the reason for them. This function should insert a new node at the beginning, if the node passed as argument is NULL, otherwise it should insert a new node after the node passed as argument.
In this snippet:
if (node == NULL){
node_t* new = create_node();
new->next = list->head;
list->head = new;
new->data = data;
}
the assignment new->next = list->head; is not correct. Any guesses?
nodein the list should also handle the case that the end of the list is reached without findingnode.-Wall -Wextra -pedantic, for VS/W3and do not accept code until it compiles without warning. (you will save yourself untold hours just by following this rule) Let your compiler help you write better code. The compiler will tell you the exact line (and often the exact starting character) for the problematic code. Never ignore a warning.