I'm a beginner who has been self-teaching for the past weeks data structures. I'm trying to create a function that inserts an integer into a linked lists in a sorted fashion.
Here's my function:
void sortedInsert(int n)
{
node *temp = malloc(sizeof(node));
temp->data= n;
//if list is empty or n is less than minimum number in the list, insert at the beggining.
if(head == NULL || n < head->data )
{
temp->next = head;
head = temp;
}
else
{
node *cur, *prev, *temp;
for (cur = head, prev = NULL
cur != NULL && cur->data < n; //if n is less than cur->value it breaks out of loop
prev = cur, cur = cur->next);
//now cur is pointing at last node or the node it broke out off
if( n < cur->data)
{
temp->next = cur;
prev->next = temp;
}
else
{
//if its larger than the maximun number in the list
//insert at end
temp->next = NULL;
cur->next = temp;
}
free(cur);
free(prev);
}
}
Output:
How many numbers?
4
Enter the number
10
List is: 10
Enter the number
4
List is: 4 10
Enter the number
5
Process returned -1073741819 (0xC0000005) execution time : 7.161 s
Press any key to continue.
It crashes out whenever I insert a number greater than those on the list. I'll appreciate any help or guidance I could get.
freein your insert functions, you are doing it wrong. Can you justify these calls?if( n < cur->data)need check ofcur != NULL2)free(cur); free(prev);are wrong. 3)for (cur = head, prev = NULL-->for (cur = head, prev = NULL;