力扣 24两两交换链表中节点

画图

注意有虚拟头结点

注意判断时先判断cur->next != nullptr,再判断cur->next->next != nullptr

注意末尾返回dumyhead->next,用新建result指针来接并返回

复制代码
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;


    }
};
相关推荐
铉铉这波能秀14 分钟前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.14 分钟前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
踢足球092917 分钟前
寒假打卡:2026-2-8
数据结构·算法
IT猿手27 分钟前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风28 分钟前
SMU-ACM2026冬训周报3rd
算法
铉铉这波能秀1 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
晚霞的不甘1 小时前
Flutter for OpenHarmony 实现计算几何:Graham Scan 凸包算法的可视化演示
人工智能·算法·flutter·架构·开源·音视频
㓗冽1 小时前
60题之内难题分析
开发语言·c++·算法
大江东去浪淘尽千古风流人物1 小时前
【VLN】VLN仿真与训练三要素 Dataset,Simulators,Benchmarks(2)
深度学习·算法·机器人·概率论·slam
铉铉这波能秀2 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary