代码随想录 Leetcode24. 两两交换链表中的节点

题目:

代码随想录 Leetcode24. 两两交换链表中的节点_第1张图片


代码(首刷看解析 2024年1月12日):

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==nullptr) return nullptr;
        ListNode* cur = new ListNode(0,head);
        ListNode* dummy = cur;
        while(cur->next != nullptr && cur->next->next != nullptr) {
            ListNode* tmp = cur->next;
            ListNode* tmp2 = cur->next->next->next;

            cur->next = cur->next->next;
            cur->next->next = tmp;
            tmp->next = tmp2;

            cur = cur->next->next;
        } 
        return dummy->next;
    }
};

        链表类题目一定要画图

你可能感兴趣的:(#,leetcode,---medium,c++,算法)