交换链表相邻节点解析
leetcode第24题链表 https://leetcode.cn/problems/swap-nodes-in-pairs/description/

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL) return NULL;
if(head->next==nullptr) return head;
//--创建虚拟头节点指向第二个节点 即真实头节点的下一个节点
ListNode* dummyHead = new ListNode(0);
dummyHead->next=head->next;
//--初始化当前节点和下一个节点
ListNode* cur=head;
ListNode* flo=head->next;
//--创建临时节点
ListNode* tmpcur; //cur下一次要移动到的节点
ListNode* tmpflo; //tmp下一次要移动到的节点
//--当前循环,后面要移动到的两个位置都不是空节点
while(flo->next!=nullptr && flo->next->next!=nullptr)
{
tmpcur=cur->next->next;//--存储下一次要移动到的节点
tmpflo=flo->next->next;//--存储下一次要移动到的节点
//--更改当前cur和flo的指向
cur->next=tmpflo;//cur->next=cur->next->next->next;
flo->next=cur;
//--更新cur和flo的位置
cur=tmpcur;
flo=tmpflo;
}
//--循环结束后的下一个节点是空
if(flo->next==nullptr)
{
flo->next=cur;
cur->next=nullptr;
}
else if(flo->next->next==nullptr && flo->next!=nullptr) //循环结束后的下一个节点不空,但下下一个节点是空
{
cur->next=flo->next;
flo->next=cur;
}
return dummyHead->next;
}
};

浙公网安备 33010602011771号