This isworking fine why this two behaviour and error im cant understand

1 2 10 12 13 15 20 40 -1
5 17 19 28 30 32 40 41 -1
check for this output the logic is wrong, why?
x= 1 y =5
small_head will get the value 2 because it is smaller one, now first condition is satisfied because x<y
so 5 points to 2 and 1 points to 5
which is wrong
correct code link: