思想:
创建一个辅助头结点简便编程。
下一轮swap中若first为NULL,则second直接设为NULL。
/**
* 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) // at least two nodes, if not, return
return head;
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *prev,*first,*second;
prev = dummy;
first = prev->next;
second = first->next;
while(second != NULL) {
prev->next = second;
first->next = second->next;
second->next = first;
prev = first;
first = first->next;
second = (first == NULL ? NULL : first->next);
}
return dummy->next;
}
};