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;
    }
};
相关推荐
青 春 记 忆2 小时前
LeetCode 350. 两个数组的交集 II|Python 解法详解
python·算法·leetcode
wuyk5553 小时前
107.FreeRTOS 链表深度解析:从原理到面试满分答案
c语言·开发语言·数据结构·stm32·单片机·链表·面试
-dzk-3 小时前
【链表】LC 138.随机链表的复制
数据结构·链表
洋不写bug4 小时前
链表补充练习,双链表的模拟实现
java·数据结构·链表·双链表·底层实现
heima20165 小时前
长期复盘:拼团活动链接开发公司的行业现状与困境洞察
链表
mmmmath_36 小时前
面试题 02.07. 链表相交
算法·链表
圣保罗的大教堂6 小时前
leetcode 3903. 最小稳定下标 I 简单
leetcode
sylviiiiiia7 小时前
Leetcode hot100 多数元素/相交链表/反转链表
算法·leetcode·链表
CoderYanger7 小时前
A.每日一题:3622. 判断整除性
java·程序人生·算法·leetcode·面试·职场和发展·蓝桥杯
rannn_1117 小时前
【力扣hot100】动态规划专题|70、118、198、279、322、139、300、152、416、32
算法·leetcode·动态规划