关键点:
对链表节点操作之前,一定要先创建临时变量保存链表元素,比如我想交换有三个元素的链表,在交换前两个元素时,一定要保存第三个元素。如果不保存,会出现空指针异常,交换后的节点没法指向第三个节点,因为链表的交换操作就像一个断链然后又接链的一个过程。
/**
* 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(0);
_dummyhead->next=head;
ListNode* cur=_dummyhead;
while(cur->next!=NULL&&cur->next->next!=NULL){
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;
}
};