I am working on a project about linked list, I have trouble with inserting a number to a sorted linked list. The number inserted to the second position every time, I cannot figure out where the problem is.Here is my code:
void insertSort(struct linkedList *n,int num,int *length){ //insert number to a sort linked list
node *new = (node *) malloc(sizeof(node)); //create a new node
new->next=NULL;
new->data = num;
while(n!=NULL&&n->data > new->data){ // find which position num should insert in sorted list
n = n->next;
}
new->next = n->next;
n->next= new;
length += 1;
}
n is head of the linked list. I initialized head points to the first node and has not value. Here is how I call this function:
insertSort(head->next,num,&length);
The number inserted to the second position every time. Like I want to insert 45 into sorted linked list <16,32,72,81,97>, after inserting, the list would be <16,45,32,72,81,97>. 45 inserts to the second position for some reason.
because you are never testing the position of the node . your code only puts the new node at 2nd position . it does not checks where it should be in the sorted list try below
The problem :
is occurring because in this part of code:
you are inserting the new node after the
n->next
.Assume the first node of your linked list is having data
16
and now you want to insert the new node with data45
in the linked list, thewhile
loop condition will fail as16 > 45
will evaluate tofalse
.And the statement after
while
loopnew->next = n->next;
will set the next of new node to next of the first node andn->next= new;
will insert the new node after first node. Hence, the new node inserted to second position every time.There are few more problems with your function
insertSort()
like:head
of the linked list while inserting a node to the linked list and,n
willNULL
and ininsertSort()
afterwhile
loop it is accessingnext
ofn
-new->next = n->next;
.Looking at the example you have given - <16,32,72,81,97>, you want to insert in ascending order. You can do:
Here, you can see that I have changed return type
void
tostruct linkedList *
so that after inserting new node to appropriate location in linked listinsertSort()
will return thehead
of the linked list. That way you can keep track ofhead
of linked list after every insertion. You just need to do:from wherever you are calling
insertSort()
.Alternatively, you can pass the address of
head
pointer ininsertSort()
and keep track of it, if you don't want to change the return type ofinsertSort()
, like this:You can call
insertSort()
like this:Hope this helps.