首页 > 代码库 > LeetCode Swap Nodes in Pairs

LeetCode Swap Nodes in Pairs

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        ListNode *a = NULL;
        ListNode *b = NULL;
        ListNode *tail = NULL;
        ListNode *nhead = NULL;
        a = head;
        while (a != NULL && (b = a->next) != NULL) {
            a->next = b->next;
            b->next = a;
            if (tail != NULL) {
                tail->next = b;
            } else {
                nhead = b;
            }
            tail = a;
            a = a->next;
        }
        if (nhead == NULL) {
            nhead = head;
        }
        return nhead;
    }
};

准备六级,水一发