利用双重指针来实现单向链表的节点交换

一道Leetcode中的题:

Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

以下是摘自讨论区的一个利用双重指针的解法:

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

输入一个链表

node1 -> node2 -> node3 -> node4

值得注意的是代码段

*pp = b;
pp = &(a->next);

第一次循环结束的时候pp指向的是node1的next指针,在第二次循环中

*pp = b;

将node1的next赋值为node4

你可能感兴趣的:(C++)