Consider a simple struct:
struct Node{
int val;
Node *next;
Node *freeNode;
};
Now I have to sort a given linked list only using freeNode and the method has to be efficient. I can't make another list and use some kind of sorted-insert there. Nor can use genome or bubble sort. The pointer freeNode of any elem in the list can be pointing to any elem in the list.
Now I have come up with two ideas:
Use freeNode to make a doubly Linked List.
And do pair comparing, i.e. compare the ith elem with the (i+1)th elem. When I find that two elements need to be swapped, I swap them and then again start from the head of the List.
This algorithm would be more than O(n) (not sure just guessing). It will take much time.
Another method is that my freeNode points to elem that is smaller than it.
E.g. if I have
30->6->14->56>Tail, then56->freeNode->14 30->freeNode->14 14->freeNode->6 6->freeNode->NULL.But again, this doesn't help much, because when I insert
45 or 20I would have to re-arrange myfreeNodepointer. And, again, it would not be a very efficient method.
Any suggestions on this? How to use freeNode to implement a better and efficient method for sorting. Pseudo-code would work, and I'd actually prefer that over real code.
EDIT: You can't use arrays, vectors or anything else. Just the freeNode pointer. Use it in any way you want. Keep it NULL or have it point to elements of your choice.