I am trying to create a program that inserts numbers into a linked list in ascending order. This is my insert function. It works for inserting some numbers but not others. I think it has something to do with the last part, but i cant figure it out.
node* insert(node* head, int value) {
//check if head hasn't been created
if (head == NULL) {
head = malloc(sizeof(node));
if(head == NULL) {
printf("Failed to create head node");
return head;
}
head->value = value;
head->next = NULL;
return head;
}
//create a new node
node *newNode;
newNode = malloc(sizeof(node));
if(newNode == NULL) {
printf("Failed to create node");
return newNode;
}
newNode->value = value;
newNode->next = NULL;
//see if new node should be placed before head
if (value < head->value) {
newNode->next = head;
return newNode;
}
//search through to find correct spot and insert the node
node *temp = NULL;
temp = head;
while(temp->next != NULL && temp->value < value) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
return head;
}
You need to check for
temp->next->value
inside the last while loop.Part of the following bad
e.g. to fix like this:
or
It would be much better if you firstly implement (and test) functions like:
push_front()
,insert()
(insert before), andpush_back()
, (probablyadvance (Node* curr, int steps);
) and then simply take into consideration all the possibilities of insertion, i.e.:push_front / back()
)advance()
) over all elements fromhead
and on, till:insert()
before it.push_back()
.in your new function
insert_ordered()
.