1.代码
/**
* 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) return nullptr;
if(head->next == nullptr) return head;
ListNode* tmp;
tmp = head->next;
ListNode* tmp2 = tmp->next;
tmp->next = head;
head->next = swapPairs(tmp2);
head = tmp;
return head;
}
};
2.思路
用了递归的想法,每一次处理开头两个结点,并调用自身处理剩余结点。