21. 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.

不能修改链表中的值,交换链表

/**
 * 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 dummy(-1);
        dummy.next = head;

        if(!head || !head->next)    return head;

        ListNode *prev = &dummy;
        while(prev->next && prev->next->next){

            ListNode *swap1 = prev->next;
            ListNode *swap2 = prev->next->next;

            prev->next = swap2;
            swap1->next = swap2->next;
            swap2->next = swap1;

            prev = swap1;
        }
        return dummy.next;
    }
};

使用二级指针

/**
 * 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 **pp = &head;
        ListNode *swap1, *swap2;

        while((swap1 = *pp) && (swap2 = swap1->next)){
            swap1->next = swap2->next;
            swap2->next = swap1;
            *pp = swap2;

            pp = &(swap1->next);
        }
        return head;
    }
};
/**
 * 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) {
        if(!head || !head->next)
            return head;

        ListNode* next = head->next;
        head->next = swapPairs(next->next);
        next->next = head;

        return next;
    }
};

results matching ""

    No results matching ""