自己想的,非递归、无需额外辅助结点(真就硬交换)
/**
* 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 * p = head;
ListNode * q = p->next;
head = q;
while(q->next!=NULL){
p->next = q->next;
q->next = p;
q = q->next->next;
if(q->next != NULL){
p->next = q->next;
p = q;
q = q->next;
}else{
return head;
}
}
q->next = p;
p->next = NULL;
return head;
}
};