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;
    }
};
相关推荐
hn小菜鸡5 小时前
LeetCode 2460.对数组执行操作
算法·leetcode·职场和发展
.YM.Z5 小时前
数据结构——链表
数据结构·链表
自信的小螺丝钉6 小时前
Leetcode 148. 排序链表 归并排序
算法·leetcode·链表·归并
1白天的黑夜16 小时前
队列+宽搜(BFS)-662.二叉树最大宽度-力扣(LeetCode)
c++·leetcode·宽度优先·队列
hn小菜鸡7 小时前
LeetCode 2570.合并两个二维数组-求和法
数据结构·算法·leetcode
hn小菜鸡7 小时前
LeetCode 524.通过删除字母匹配到字典里最长单词
算法·leetcode·职场和发展
滋滋不吱吱8 小时前
栈的进阶篇
数据结构·算法·leetcode
小欣加油9 小时前
leetcode 98 验证二叉搜索树
c++·算法·leetcode·职场和发展
爱编程的化学家9 小时前
代码随想录算法训练营第21天 -- 回溯4 || 491.非递减子序列 / 46.全排列 /47.全排列 II
数据结构·c++·算法·leetcode·回溯·全排列·代码随想录