题目
swap-nodes-in-pairs
算法
* 迭代
* 递归
代码
* 迭代
class Solution{
public:
ListNode* swapPairs(ListNode* head){
ListNode* dummy=new ListNode(-1), *pre=dummy;
dummy->next=head;
while(pre->next && pre->next->next){
ListNode* t=pre->next->next;
pre->next->next=t->next;
t->next=pre->next;
pre->next=t;
pre=t->next;
}
return dummy->next;
}
};
* 递归
class Solution{
public:
ListNode* swapPairs(ListNode* head){
if(!head||!head->next) return head;
ListNode* t=head->next;
head->next=swapPairs(head->next->next);
t->next=head;
return t;
}
};