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.

注意:交换两个结点后,注意next的指向,注意二级指针的用法,在“Remove Linked List Elements(移除列表中指定的元素”也有使用到二级指针。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    ListNode* swapPairs(ListNode* head) 
    {
        ListNode **p = &head, *a, *b;
        while ((a = *p) && (b = a->next)) 
        {
            a->next = b->next;
            b->next = a;
            *p = b;
            p = &(a->next);
        }
        return head;
    }
};

你可能感兴趣的:(List)