Leetcode 4. 两两交换链表中的节点 递归 / 迭代

原题链接:4. 两两交换链表中的节点

递归

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) return head;
        if(head->next==nullptr) return head;
        ListNode* root = head->next;
        head->next=swapPairs(root->next);
        root->next = head;
        return root;
    }
};

迭代:

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) return head;
        if(head->next==nullptr) return head;
        ListNode* root = head->next;
        ListNode* node1 = head;
        ListNode* pre = nullptr;
        while(node1){
            ListNode* node2 = node1->next;
            if(node2==nullptr) break;
            node1->next = node2->next;
            node2->next = node1;
            if(pre) pre->next = node2;
            pre = node1;
            node1 = pre->next;
        }
        return root;
    }
};
相关推荐
元亓亓亓4 分钟前
LeetCode热题100--70. 爬楼梯--简单
算法·leetcode·职场和发展
一起养小猫7 分钟前
LeetCode100天Day3-判断子序列与汇总区间
java·数据结构·算法·leetcode
YGGP27 分钟前
【Golang】LeetCode 75. 颜色分类
算法·leetcode
soft200152534 分钟前
MySQL Buffer Pool性能优化:LRU链表极致设计之道
数据库·mysql·链表
杜子不疼.1 小时前
【LeetCode 704 & 34_二分查找】二分查找 & 在排序数组中查找元素的第一个和最后一个位置
算法·leetcode·职场和发展
LYFlied1 小时前
【每日算法】LeetCode 437. 路径总和 III
前端·算法·leetcode·面试·职场和发展
alphaTao4 小时前
LeetCode 每日一题 2025/12/15-2025/12/21
算法·leetcode
LYFlied11 小时前
【算法解题模板】动态规划:从暴力递归到优雅状态转移的进阶之路
数据结构·算法·leetcode·面试·动态规划
风筝在晴天搁浅15 小时前
hot100 239.滑动窗口最大值
数据结构·算法·leetcode
LYFlied15 小时前
【算法解题模板】-解二叉树相关算法题的技巧
前端·数据结构·算法·leetcode