Reputation: 248
I'm trying to swap two pointers of a singly linked list using the bubble sort.
I've made the compare function, and its working good.
In the swap function, the swap is working good, I've managed to swap between the node and the node->next
, though the linked list "lose" the info of the node (after the swap), so the first node in the linked list is node->next
.
I'm using a generic function which do the bubble sort and call the compare function and the swap function.
Any idea why this happens?
void swap_arr(void **arr,int i , int j)
{
Team *teamList = (Team*) arr ;
Team *teamI = (Team*) arr , *teamJ ;
Team *temp ;
Team *temp1;
int z;
// Receives instead i
for(z=0; z<i; z++)
teamI = teamI->next;
//teamJ is the i+1
teamJ = teamI->next;
temp = teamI;
temp1 = teamJ->next;
teamI = teamJ ;
teamJ = temp;
if (temp1->next->next==NULL)
teamJ->next = NULL;
else
teamJ->next = temp1->next;
teamI->next = teamJ;
if (temp1==NULL)
teamJ->next=NULL;
else
teamJ->next = temp1;
}
Upvotes: 1
Views: 3712
Reputation: 134
I was also trying to implement sorting of linkedlist using bubble sort, though the modification you can do in your code would be rather than writing a swap function you could just swap them in your code only and each time you would need to have 3 different pointers pointing to adjacent nodes. You can find the implemented code here.
Upvotes: 0
Reputation: 44250
For swapping two nodes (a,b), you need access to an "outside" node (o), which points to the first. (and there is also a node p after a and b. (p could be NULL, too, but that is not important)
Old situation:
o->next == a
a->next == b
b->next == p
New situation:
o->next == b
b->next == a
a->next == p
This swap can only be performed if o actually is a node. (and thus: has an o->next pointer), so you'll need special code to handle the case where a is the head of the chain.
But no: o->next is only a "struct llist *", so any pointer to a llist can be used. In most cases, the simplest solution is to use a pointer-to-pointer argument for the swap function; a pointer-to-pointer can either point to the head of the chain, or to some node's ->next pointer.
Upvotes: 3