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

递归

交换前面的节点之前必须先交换完后面的,否则无法确定第二个元素的 next 指针
故递归可解

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
        
        ListNode* second =  head->next;
        head->next = swapPairs(head->next->next);
        second->next = head;
        
        return second;
    }
};

迭代

ListNode *swapPairs(ListNode *head) {
    ListNode *dummy = new ListNode(0), *node;
    node = dummy;
    dummy->next = head;
    while (head && head->next) {
        ListNode *nxt = head->next;
        head->next = nxt->next;
        nxt->next = head;
        node->next = nxt;
        node = head;
        head = node->next;
    }
    return dummy->next;
}

你可能感兴趣的:(24. Swap Nodes in Pairs)