Im trying to do a bubble sort on a linked list using pointer
I\'m trying to do a bubble sort on a linked list using pointers. I can change the order of the nodes but I cannot change the contents of the nodes. If you have sample code for a bubble sort on a linked list, that would be extremely helpful.
Solution
Here is the below code for the above scenario:
void linked_list::sort ()
{
int count = 0, i;
node *start = head;
node *curr = NULL;
node *trail = NULL;
node *temp = NULL;
while(start != NULL)
{
count++;
start = start->next;
}
for(i = 0; i<count; ++i)
{
curr = trail = head;
while (curr->next != NULL)
{
if (curr->data > curr->next->data)
{
temp = curr->next;
curr->next = curr->next->next;
temp->next = curr;
if(curr == head)
head = trail = temp;
else
trail->next = temp;
curr = temp;
}
trail = curr;
curr = curr->next;
}
}
}

