Below code is copy from geekforgeeks. I'm curious about the swap It didn't change the previous node's next. Why can it still print the right answer after sort? If it has change previous node's next link, then where?
Thanks for answering.
struct Node* swap(struct Node* ptr1, struct Node* ptr2)
{
struct Node* tmp = ptr2->next;
ptr2->next = ptr1;
ptr1->next = tmp;
return ptr2;
}
int bubbleSort(struct Node** head, int count)
{
struct Node** h;
int i, j, swapped;
for (i = 0; i <= count; i++) {
h = head;
swapped = 0;
for (j = 0; j < count - i - 1; j++) {
struct Node* p1 = *h;
struct Node* p2 = p1->next;
if (p1->data > p2->data) {
/* update the link after swapping */
*h = swap(p1, p2);
swapped = 1;
}
h = &(*h)->next;
}
/* break if the loop ended without any swap */
if (swapped == 0)
break;
}
}