I am trying to sort a singly linked list using bubble sort by manipulating ONLY the pointers, no keys.
The following gets stuck in the for loop and loops infinitely. I don't understand why this is. Can anybody explain to me why the end of the list is not being found?
Node* sort_list(Node* head)
{
Node * temp;
Node * curr;
for(bool didSwap = true; didSwap; ) {
didSwap = false;
for(curr = head; curr->next != NULL; curr = curr->next) {
if(curr->key > curr->next->key) {
temp = curr;
curr = curr->next;
curr->next = temp;
didSwap = true;
}
cout << curr->next->key << endl;
}
}
return head;
}
If I change the code so that the keys (data) are swapped, then the function works properly but for some reason I am not able make it work by manipulating only pointers.
The field you want to swap is the
value
. However, if you swap thenode
, thenext
field will change, the question becomes a little more complex, you need keep thenext
field right. In a word, changevalue
is a simple and good method.Logical Error, you are creating an infinite loop with following code -
I,e next_of_current is pointing to current, so curr->next will always be curr and never will be NULL;
Next you should use previous pointer to fix your list because your list can be traversed in a single direction. So, Think - If A->B->C->NULL; and you make C and B swap then the new list will still point to A->B and next iteration will be wrong ... because you are not modifying your previous next.
So, another implementation may be -
Hope this helps, regards.
You have following problem:
Let you have list with three members:
ptr1->ptr2->ptr3
. Before swap you have following pointer set:curr=ptr1; curr->next=ptr2; curr->next->next=ptr3
. When you perform swap you receivecurr=ptr2; curr->next=ptr1; curr->next->next=ptr2
.E.g. you lost ptr3. You need to change code of inner loop with following: