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;
    }
};
相关推荐
z1874610300314 小时前
list(带头双向循环链表)
数据结构·c++·链表
sin_hielo14 小时前
leetcode 1611
算法·leetcode
来荔枝一大筐15 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
小白程序员成长日记16 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白16 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
小白程序员成长日记17 小时前
2025.11.08 力扣每日一题
算法·leetcode·职场和发展
他们叫我一代大侠19 小时前
Leetcode :模拟足球赛小组各种比分的出线状况
算法·leetcode·职场和发展
海琴烟Sunshine19 小时前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode
一只鱼^_1 天前
力扣第 474 场周赛
数据结构·算法·leetcode·贪心算法·逻辑回归·深度优先·启发式算法
程序员东岸1 天前
数据结构杂谈:双向链表避坑指南
数据结构·链表