递归做法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode *next = head->next;
head->next = swapPairs(next->next);
next->next = head;
return next;
}
};
非递归做法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode*extra = new ListNode(-1);
extra->next = head;
ListNode *preP=extra;
ListNode *p = head;
ListNode *q;
while(p!=NULL&&p->next!=NULL){
q=p->next;
//开始交换
p->next = q->next;
q->next = p;
preP->next = q;//交换完毕
preP=p;
p=preP->next;
}
return extra->next;
}
};