这题写的时间有点长, 犹豫了很久。 还是对指针的操作不够熟练, 以前也没怎么练习过操作指针。 看来是要专门练一下。思路比较简单
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
void deal(ListNode * bef, ListNode * l1, ListNode * l2){
l1->next = l2->next;
l2->next = l1;
bef->next = l2;
}
public:
ListNode *swapPairs(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == 0 || head->next == 0)
return head;
ListNode * ret = head->next;
// swap the first two
head->next = ret->next;
ret->next = head;
// swap the other
ListNode * bef = ret->next;
ListNode* a[2];
int now = 1;
ListNode * p = bef;
while(p->next != 0){
p = p->next;
now = (now + 1) % 2;
a[now] = p;
if(now == 1){
deal(bef, a[0], a[1]);
bef = p = a[0];
}
}
return ret;
}
};