[LeetCode]Swap Nodes in Pairs题解

Swap Nodes in Pairs:

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.

这道题我尝试写了用两个指针交换的方法,结果Runtime error了。

最后看了Discuss的解答,整理一下思路。首先,用指针的指针pp指向头部,a和b分别指向当前的node节点的指针指向下一个节点的指针。而我们要做到的是把 *pp == a -> b -> (b->next) 转换成 *pp == b -> a -> (b->next)。事实上代码中while循环内前三行做的就是这个任务。

代码如下:

class Solution {
public:
    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;
    }
};
posted @ 2017-10-09 23:44  liangf27  阅读(82)  评论(0编辑  收藏  举报