画图
注意有虚拟头结点
注意判断时先判断cur->next != nullptr,再判断cur->next->next != nullptr
注意末尾返回dumyhead->next,用新建result指针来接并返回
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode *cur = dummyhead;
while(cur->next != nullptr && cur->next->next !=nullptr)
{
ListNode *tmp = cur->next;
ListNode *tmp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
cur->next->next->next = tmp1;
cur = cur->next->next;
}
ListNode *result = dummyhead->next;
delete dummyhead;
return result;
}
};