注意:要操作 一个结点的指针指向 就记得要知道 这个结点的前一个结点指针
因此什么时候要引入虚拟指针,为什么需要呢?
因为我们需要改变头结点的指针指向
/**
* 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) {
ListNode *dummyhead=new ListNode();
dummyhead->next=head;
ListNode*cur=new ListNode();
cur=dummyhead;
while(cur->next!=nullptr&&cur->next->next!=nullptr){
ListNode*temp=cur->next;
ListNode*temp1=cur->next->next->next;
cur->next=cur->next->next;
cur->next->next =temp;
temp->next=temp1;
cur=cur->next->next;
}
return dummyhead->next;
}
};