思路
virtual_head作为临时节点保存交换过的链表的尾部,使得left和right进行交换之后能够连接到原链表的尾部
效果
代码
struct ListNode* swapPairs(struct ListNode* head){
if(head==NULL || head->next==NULL) return head;
struct ListNode *left=head,*right=head->next;
left->next=right->next;
right->next=left;
head=right;
struct ListNode *virtual_head=left;
while(virtual_head->next!=NULL && virtual_head->next->next!=NULL){
left=virtual_head->next;
right=left->next;
left->next=right->next;
right->next=left;
virtual_head->next=right;
virtual_head=left;
}
return head;
}
|