题目描述


代码
cpp
/**
* 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==nullptr || head->next == nullptr)
return head;
ListNode *dummyHead = new ListNode(-1,head);
ListNode *pre = dummyHead;
ListNode *newHead = nullptr;
ListNode *post;
while(pre->next != nullptr && pre->next->next != nullptr){
ListNode *pair1 = pre->next;
ListNode *pair2 = pre->next->next;
if(newHead == nullptr)
newHead = pair2;
post = pair2->next;
pair2->next = pair1;
pair1->next = post;
pre->next = pair2;
pre = pair1;
}
delete dummyHead;
dummyHead = nullptr;
return newHead;
}
};