Sort linked list using insertion sort

CODE LINK : https://pastebin.com/ZDxuBeMG
in my insertion sort function why value of current gets changed here before and after I am calling the sorted function, as in other function I am sending it’s copy and not the reference , please explain

Hello @Divya_321

consider the linked list is 3 5 7 1 9 and head2 = 3 (first Node) && current = 6 (fourth Node)
In your code

if (head2 == NULL || head2->data > current->data) {
    current->next = head2;
    head2 = current;
}

The above if condition will run because head2->data > current->data
Inside the if condition there are two statements
current->next = head2; // 1 ->3
head2 = current; head2 is 1

but the link from 7 to 9 is broken, you need to maintain that link also.

Let me know if you still need any help.

but I don’t need to maintain that link if say from first 3 is considered that time head2 is null it becomes head, than 5 comes in but if condition doesn’t satisfy so 5 gets added to 3 ,3->5, same for 7, 3->5->7, and when 1 comes in than if condition is satisfied current node holding 1 here points to 3 , and head2 is assigned current node , than here node containing 3 here already has link of rest of the nodes and it becomes 2->3->5->7 and then goes to else condition,

the code absolutely works fine when in sorted function I am doing n = current->next; fnCall(); then current = n; but not when current = current->next after fn call, I am unable to understand y value of current gets, changed overhere, although it 's not passed with reference

Hello @Divya_321

Your “sorted” function is correct but “insertionSort” is Not.
When you pass the node “current” to the function “sorted” in line 69, the node “current” is modified and it no more points to its next node. So line 70 doesn’t work the way it should.
I (in the modified code) used a variable “current” to store the address of the current node and the variable “nextNode” to store the address of the next node.

Here is the modified code

Let me know if you still need any help.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.