两两交换链表中的节点

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


题目:


示例:


思路:

这个题有点类似于反转一个单链表,不同的地方在于这个题不全反转,所以我们不同的地方在于此题多用了一个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宝啊

愿所有美好如期而遇

相关推荐
denggun123458 小时前
悬垂指针 和 野指针
数据结构
Pluto_CSND8 小时前
JSONPath解析JSON数据结构
java·数据结构·json
无限进步_8 小时前
【C语言】用队列实现栈:数据结构转换的巧妙设计
c语言·开发语言·数据结构·c++·链表·visual studio
liu****8 小时前
02_Pandas_数据结构
数据结构·python·pandas·python基础
optimistic_chen8 小时前
【Redis 系列】常用数据结构---Hash类型
linux·数据结构·redis·分布式·哈希算法
五阿哥永琪9 小时前
Redis的常用数据结构
数据结构·数据库·redis
Sheep Shaun9 小时前
STL中的map和set:红黑树的优雅应用
开发语言·数据结构·c++·后端·c#
H_BB9 小时前
leetcode160:相交链表
数据结构·算法·链表
浅川.2510 小时前
STL专项:queue 队列
数据结构·stl·queue
企鹅侠客11 小时前
第06章—实战应用篇:List命令详解与实战(上)
数据结构·windows·redis·list