24. 两两交换链表中的节点
卡哥的讲解很详细了
卡哥视频讲解一如既往的把小细节都讲到了
跟着卡哥的代码敲了下
/**
* 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) {
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;
}
};
再附上自己刚开始理解过程中的一个误区