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;
    }
};
相关推荐
参.商.7 小时前
【Day41】143. 重排链表
leetcode·golang
Zaly.10 小时前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
计算机安禾10 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
memcpy012 小时前
LeetCode 1456. 定长子串中元音的最大数目【定长滑窗模板题】中等
算法·leetcode·职场和发展
玛丽莲茼蒿12 小时前
LeetCode hot100【相交链表】【简单】
算法·leetcode·职场和发展
wen__xvn12 小时前
力扣模拟题刷题
算法·leetcode
不要秃头的小孩13 小时前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
We་ct13 小时前
LeetCode 35. 搜索插入位置:二分查找的经典应用
前端·算法·leetcode·typescript·个人开发
Navigator_Z14 小时前
LeetCode //C - 990. Satisfiability of Equality Equations
c语言·算法·leetcode
Book思议-15 小时前
【数据结构实战】双向链表:在指定位置插入数据
c语言·数据结构·算法·链表