原题链接:4. 两两交换链表中的节点
递归
cpp
/**
* 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 head;
if(head->next==nullptr) return head;
ListNode* root = head->next;
head->next=swapPairs(root->next);
root->next = head;
return root;
}
};
迭代:
cpp
/**
* 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 head;
if(head->next==nullptr) return head;
ListNode* root = head->next;
ListNode* node1 = head;
ListNode* pre = nullptr;
while(node1){
ListNode* node2 = node1->next;
if(node2==nullptr) break;
node1->next = node2->next;
node2->next = node1;
if(pre) pre->next = node2;
pre = node1;
node1 = pre->next;
}
return root;
}
};