1

I met this problem of swapping consecutive two nodes from beginning to end of a linked list.(Eg. [1,2,3,4] to [2,1,4,3] or [1,2,3,4,5] to [2,1,4,3,5]) I found the pointer to pointer solution hard to understand. Can anyone help me on the following codes

ListNode* swapPairs(ListNode* head) {
    ListNode **pp = &head, *a, *b;
    while ((a = *pp) && (b = a->next)) {
        a->next = b->next;
        b->next = a;
        *pp = b;
        pp = &(a->next);
    }
    return head;
}

I can't understand the line *pp = b. why it only changes the 'head' to 'b' but keeps 'a' untouched? when debugging, 'a' and 'head' are the same before this line.

tkausl
  • 13,686
  • 2
  • 33
  • 50
YYX
  • 11
  • 1
  • Er. Because they're separate variables? Why would setting one variable change another variable (even if that other variable happens to have the same value)? – melpomene Jun 25 '16 at 21:51
  • Thanks. I think I found out the reason. The addresses of 'a' and 'head' are different and pp only points to head. I only checked the value of 'a' and head which is a mistake. – YYX Jun 25 '16 at 21:55
  • Please consider answering your own question. – 2501 Jun 26 '16 at 10:12

0 Answers0