题目描述
方法一:递归
class Solution{
public:
ListNode* swapPairs(ListNode* head){
if(!head || !head->next){
return head;
}
ListNode* newHead = head->next;
head->next = swapPairs(newHead->next);
newHead->next = head;
return newHead;
}
};
方法二:迭代
class Solution{
public:
ListNode* swapPairs(ListNode* head){
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* temp = dummy;
while(temp->next!=NULL && temp->next->next!=NULL){
ListNode* node1 = temp->next;
ListNode* node2 = temp->next->next;
temp->next = node2;
node1->next = node2->next;
node2->next = node1;
temp = node1;
}
return dummy->next;
}
};