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;
    }
};
相关推荐
文丑颜不良啊3 小时前
LeetCode2081~2100题目解析
java·leetcode
文丑颜不良啊4 小时前
LeetCode2061~2080题目解析
java·leetcode
文丑颜不良啊17 小时前
LeetCode1941~1960题目解析
java·leetcode
文丑颜不良啊21 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2001~2020题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2021~2040题目解析
java·leetcode
Nuanyt2 天前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
圣保罗的大教堂2 天前
leetcode 3736. 最小操作次数使数组元素相等 III 简单
leetcode
文丑颜不良啊2 天前
LeetCode1881~1990题目解析
java·leetcode