还是很简单的链表链接问题,不过中间我设置指针翻转的时候还是出了一些问题。值得小心
/**
* 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;
}else{
ListNode* _head = new ListNode;
_head->next = head;
ListNode* cur;
ListNode* _next;
head = _head;
cur = head->next;
_next = cur->next;
while(cur!=nullptr && cur->next != nullptr){
cur = head->next;
_next = cur->next;
cur->next = _next->next;
head->next = _next;
_next->next = cur;
head = cur;
cur = head->next;
if(cur == nullptr || cur->next == nullptr){
return _head->next;
}else{
_next = cur->next;
}
}
}
return head;
}
};