---
# System prepended metadata

title: 0024. Swap Nodes in Pairs
tags: [Leetcode, Linked List, Medium]

---

# 0024. Swap Nodes in Pairs
###### tags: `Leetcode` `Medium` `Linked List`
Link: https://leetcode.com/problems/swap-nodes-in-pairs/
##  思路
###  思路一
遍历，两两一组做交换
###  思路二
递归（感觉linked list的题蛮多用递归做的）
## Code
### 思路一
```c=
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummy = new ListNode;
        dummy->next = head;
        head = dummy;
        while(head->next!=nullptr&&head->next->next!=nullptr){
            ListNode* temp1 = head->next;
            ListNode* temp2 = head->next->next;
            head->next = temp2;
            temp1->next = temp2->next;
            temp2->next = temp1;
            head = temp1;
        }
        return dummy->next;
    }
};
```
### 思路二
```c=
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == nullptr || head->next == nullptr){
            return head;
        }
        ListNode* newHead = head->next;
        head->next = swapPairs(newHead->next);
        newHead->next = head;
        return newHead;
    }
};
```
## Result
### 思路一
Runtime: 4 ms, faster than **57.37%** of C++ online submissions for Swap Nodes in Pairs.
Memory Usage: 7.6 MB, less than **45.78%** of C++ online submissions for Swap Nodes in Pairs.
### 思路二
Runtime: 0 ms, faster than **100.00%** of C++ online submissions for Swap Nodes in Pairs.
Memory Usage: 7.6 MB, less than **45.78%** of C++ online submissions for Swap Nodes in Pairs.