链表-24.两两交换链表中的结点-力扣(LeetCode)

一、题目解析

1、不能修改节点内部值

2、节点个数为0,100

二、算法原理

解法:循环(模拟)

1、结点个数特殊处理

当结点个数为0or1时,直接返回head即可

2、定义4个指针

tail、cur1、cur2和nnext,用于交换和链接前后节点

3、循环条件

观察到只有cur1和cur2都不为nullptr时,循环才会继续

4、cur1和cur2特殊情况判断

1、cur1为nullptr时,可以跳出循环直接返回结果,即只有两个结点交换

2、cur1不为nullptr时,更新cur2=cur1->next

3、cur2为nullptr时,nnext不更新

4、cur2不为nullptr时,更新nnext=cur2->next

5、返回结果

我们定义了哨兵位结点newhead,直接返回newhead->next

三、代码示例

cpp 复制代码
class Solution {
public:
    ListNode* swapPairs(ListNode* head)
    {
        if(head == nullptr || head->next == nullptr) return head;//0or1个节点
        ListNode* newhead = new ListNode();
        ListNode* tail = newhead;
        ListNode* cur1 = head;
        ListNode* cur2 = head->next;
        ListNode* nnext = cur2->next;
        while(cur1!=nullptr && cur2!=nullptr)
        {
            tail->next = cur2;
            cur2->next = cur1;
            cur1->next = nnext;
            tail = cur1;
            cur1=cur1->next;
            if(cur1 == nullptr) break;
            else cur2 = cur1->next;
            if(cur2 != nullptr) 
                nnext = cur2->next;
        }
        return newhead->next;    
    }
};

看到最后,如果对您有所帮助,还请点赞、收藏和关注,我们下期再见!

相关推荐
m0_547486662 天前
《数据结构教程》全套 PPT课件2026
数据结构
旖旎夜光2 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
CoderYanger2 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂2 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_102 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
tryxr2 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_32 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.2 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好2 天前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法