思路:
找到规律,移动指针。链表的问题只要画好图就很容易。
代码:
/**
* 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 || !head->next) return head;
auto dummy = new ListNode(-1);
dummy->next = head;
auto cur = dummy;
while(cur->next && cur->next->next){
auto tmp1 = cur->next;
auto tmp2 = cur->next->next;
cur->next = tmp2;
tmp1->next = tmp2->next;
tmp2->next = tmp1;
cur = tmp1;
}
return dummy->next;
}
};
评论区