题目


知识点
虚拟头节点
思路
注意交换的是整个结点,不是数值

错误
空指针异常
while (cur->next && cur->next->next) { }
不能交换cur->next和cur->next->next,要是交换了,可能会找不到cur->next而发生空指针异常。
代码
cpp
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
//不能交换顺序,不然cur->next->next走到cur->next的时候就可能空,发生空指针异常
while (cur->next && cur->next->next) {
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 dummy->next;
}
};