调通花了一些周折。下次应该认真回顾一下这种链表+指针反转的操作。
解法1:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode* node=head;
ListNode* newHead=head->next;
while(node && node->next) {
ListNode *temp = node->next->next;
node->next->next = node;
if (temp&&temp->next) node->next=temp->next;
else if (temp&&!temp->next) node->next=temp;
else node->next=NULL;
node=temp;
}
return newHead;
}
int main()
{
ListNode a(1);
ListNode b(2);
// ListNode c(3);
// ListNode d(4);
a.next=&b;
// b.next=&c;
// c.next=&d;
ListNode *h=swapPairs(&a);
cout<<"~~~~~~~"<<endl;
while(h) {
cout<<h->val<<" ";
h=h->next;
}
cout<<endl;
return 0;
}
解法2:递归。在Leetcode网上看到一个solution很不错,非常精巧。
ListNode* swapPairs(ListNode* head) {
ListNode *l=head;
if(head&&head->next){
l=head->next;
head->next=swapPairs(l->next);
l->next=head;
}
return l;
}