【剑斩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;
    }
};
相关推荐
政企项目老覃4 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水4 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR4 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵5 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽5 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2085 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
203号居民7 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean21037 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil2088 小时前
leetcode 78子集
数据结构·算法·leetcode