方法一 迭代
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head||!head->next)
{
return head;
}
ListNode*pre=new ListNode(0,head);
ListNode*a=pre;
while(a->next&&a->next->next)
{
ListNode*node1=a->next;
ListNode*node2=a->next->next;
ListNode*node3=a->next->next->next;
a->next=node2;
node1->next=node3;
node2->next=node1;
a=node1;
}
return pre->next;
}
};
依次迭代
递归
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head||!head->next)
{
return head;
}
ListNode*a=head->next;
ListNode*subres=swapPairs(a->next);//subres表示a->next和a->next->next 交换后的首节点
head->next=subres;
a->next=head;//交换节点;
return a;//返回首节点
}
};