https://leetcode-cn.com/problems/swap-nodes-in-pairs/
指针指的有点烦,在纸上多画画就好
ListNode* swapPairs(ListNode* head) {
if(!head||!head->next) return head;
ListNode* newhead=new ListNode(-1);//虚拟头节点
auto pre=newhead;//已经被反转链表的尾节点
ListNode* p=head; //当前节点
auto q=p; //保存后继节点
while(p){
if(!p->next){
pre->next=p;
return newhead->next;
}
q=p->next->next;
p->next->next=p;
pre->next=p->next;
p->next=nullptr;
pre=p;
p=q;
}
q=newhead->next;
delete newhead;
return q;
}