答案里有用二级指针的,也能解决指针赋值时的问题,但是我不太懂这块,实在想不到。递归也可以做,但是不知道代码怎么写,网上参考了一个才稍有理解
ListNode* swapPairs(ListNode* head) {
if(head == NULL)return NULL;
if(head->next == NULL)return head;
ListNode* newHead = head->next;
head->next = swapPairs(newHead->next);
newHead->next = head;
return newHead;
}
新增
后来又想出了不用二级指针的做法,只要多传一个指针,就能解决相邻两对node不能链接的问题
ListNode* swapPairs(ListNode* head) {
ListNode* newhead = head->next;
ListNode* front = head;
ListNode* back = head->next;
ListNode* pre_front = front;
while(1){
cout << "head " << head->val << endl;
front->next = back->next;
back->next = front;
if(front != head)pre_front->next = back;
if(front->next == NULL)break;
pre_front = front;
front = front->next;
back = front->next;
}
return newhead;
}