两两交换链表中的节点

你存在,我深深的脑海里~


题目:


示例:


思路:

这个题有点类似于反转一个单链表,不同的地方在于这个题不全反转,所以我们不同的地方在于此题多用了一个prve指针保存n1的前一个节点,以及头的改变,用newhead保存一个新的头,其他都大同小异,参考:反转一个单链表


代码:

复制代码
struct ListNode* swapPairs(struct ListNode* head)
{
    if (head == NULL)
        return NULL;

    struct ListNode* newhead = head;

    struct ListNode* n1 = head;
    struct ListNode* n2 = NULL;
    struct ListNode* n3 = NULL;

    struct ListNode* prve = NULL;
    while (n1 && n1->next)
    {

        n2 = n1->next;
        n3 = n2->next;
        if (n1 == head)
        {
            n1->next = n2->next;
            n2->next = n1;
            newhead = n2;
        }
        else
        {
            n1->next = n2->next;
            n2->next = n1;

            prve->next = n2;
        }
        prve = n1;
        n1 = n3;
    }

    return newhead;
}

个人主页:Lei宝啊

愿所有美好如期而遇

相关推荐
Hello eveybody3 小时前
C++介绍整数二分与实数二分
开发语言·数据结构·c++·算法
梦境虽美,却不长5 小时前
数据结构 学习 队列 2025年6月14日 11点22分
数据结构·学习·队列
GalaxyPokemon6 小时前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
hy.z_7778 小时前
【数据结构】 优先级队列 —— 堆
数据结构
你的牧游哥8 小时前
前端面试题之将自定义数据结构转化成DOM元素
数据结构
float_六七9 小时前
Redis:极速缓存与数据结构存储揭秘
数据结构·redis·缓存
徐新帅9 小时前
基于 C 语言的图书管理系统开发详解
c语言·开发语言·数据结构
勇闯IT9 小时前
有多少小于当前数字的数字
java·数据结构·算法
এ᭄画画的北北10 小时前
力扣-279.完全平方数
数据结构·算法·leetcode
GalaxyPokemon11 小时前
LeetCode - 69. x 的平方根
java·数据结构·算法