【剑斩OFFER】算法的暴力美学——两两交换链表中的结点

一、题目描述

二、算法原理

思路:引入哨兵位 + 3 个指针

为什么要引入哨兵位?当我们实现完第一次交换时:

prev 的 next 要指向 cur ,所以引入哨兵位,这样一次循环就能搞定交换两两结点;这里我为什么要引入 nnext ?其实是为了方便对两个结点时的交换。

循环结束的条件:

当结点为偶数时:next == nullptr 就结束循环

当结点为奇数时:cur == nullptr 就结束循环

三、代码实现

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == nullptr || head->next == nullptr) return head;
        ListNode* prev = new ListNode(0,head);
        ListNode* cur = head,*next = head->next,*nnext = next->next,*ret = next;
        while(cur && next)
        {
            next->next = cur;
            cur->next = nnext;
            prev->next = next;//对交换后的结点进行连接
            prev = cur;//开始更新 cur 、prev 、 next 、nnext
            cur = nnext;
            if(cur) next = cur->next;
            else break;
            if(next) nnext = next->next;
        }
        return ret;
    }
};

探索性代码:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* ret = nullptr;
        if(head == nullptr || head->next == nullptr) return head;
        else ret = head->next;//保存第一次交换的头结点
        ListNode* prev = head;
        ListNode* cur = head->next;
        ListNode* tmpnode = nullptr;
        ListNode* swapnode = nullptr;//保存交换后的prev
        while(cur != nullptr)//使用临时变量来进行两两交换
        {
            tmpnode = cur->next;
            cur->next = prev;
            prev->next = tmpnode;
            if(swapnode) swapnode->next = cur;//第二次,两两交换时,要把 prev 前一个结点链接上交换后的 cur
            swapnode = prev;
            prev = tmpnode;
            if(prev)
                cur = prev->next;
            else break;
        }
        return ret;
    }
};
相关推荐
vibecoding日记6 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21388 小时前
Verilog参数化游程编码RLE模块
算法
望易9 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络13 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望2 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法