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;
    }
};
相关推荐
Navigator_Z1 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2081 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2082 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2082 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
局部有解7 小时前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil2089 小时前
leetcode 75颜色分类
数据结构·算法·leetcode
aqiu11111110 小时前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表
不会就选b10 小时前
算法日常・每日刷题--<动态规划>29
数据结构·算法·leetcode
虚无的纽扣12 小时前
【力扣刷题】第五天:将 x 减到 0 的最小操作数、最大连续1的个数 III
算法·leetcode·职场和发展
hanlin0321 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode