why this swap dont have to change previous link but still can run

Viewed 44

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;
    }
}
1 Answers

It didn't change the previous node's next.

It changes due to the assignment

*h = swap(p1, p2);

The double pointer h points to the data member next of the previous node or to the pointer head passed to the function by reference indirectly through pointer to it die to this statement

h = &(*h)->next;

After this assignment

*h = swap(p1, p2);

the data member next of the previous node gets the value of the pointer p2. The data member next of the node pointed to by the pointer p2 gets the value of the pointer p1 and the data member next of the node pointed to by the pointer p1 gets the initially stored value of the data member next of the node pointed to by the pointer p2.

Related