每日OJ题_链表②_力扣24. 两两交换链表中的节点

目录

[力扣24. 两两交换链表中的节点](#力扣24. 两两交换链表中的节点)

解析代码


力扣24. 两两交换链表中的节点

24. 两两交换链表中的节点

难度 中等

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

复制代码
输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

复制代码
输入:head = []
输出:[]

示例 3:

复制代码
输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100]
  • 0 <= Node.val <= 100
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) {

    }
};

解析代码

递归法在下面链接讲过:

Offer必备算法07_递归_五道力扣题详解(由易到难)-CSDN博客

迭代法就是自己画图,不要吝啬定义指针,直接定义四个指针,在前面new一个头结点视为prev,让cur和next1交换,然后四个指针像后走,结束条件是cur或者next1为空。

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) {
        ListNode *newHead = new ListNode(0);
        if(head == nullptr || head->next == nullptr)
            return head;
        // newHead -> 1 -> 2 -> 3
        // 1和2换 -> cur和next1换
        // prev -> cur -> next1 -> next2
        // cur -> prev -> next1 -> next2
        ListNode *prev=newHead, *cur=head, *next1=head->next, *next2=next1->next;
        while(cur && next1)
        {
            prev->next = next1;
            next1->next = cur;
            cur->next = next2;

            prev = cur;
            cur = next2;
            if(cur)
                next1 = cur->next;
            if(next1)
                next2 = next1->next;
        }
        cur = newHead->next;
        delete newHead;
        return cur;
        // 递归法
        // if(head == nullptr || head->next == nullptr)
        //     return head;
        // ListNode* tmp = swapPairs(head->next->next); // 把两个结点之外的看成另一部分
        // head->next->next = head;
        // auto ret = head->next; // 保存一下要返回的结点
        // head->next = tmp;
        // return ret;
    }
};
相关推荐
木尼1233 小时前
leedcode 算法刷题第三十一天
算法·leetcode·职场和发展
长安——归故李4 小时前
【modbus学习】
java·c语言·c++·学习·算法·c#
索迪迈科技4 小时前
STL库——map/set(类函数学习)
开发语言·c++·学习
Dfreedom.4 小时前
在Windows上搭建GPU版本PyTorch运行环境的详细步骤
c++·人工智能·pytorch·python·深度学习
Boop_wu4 小时前
[数据结构] LinkedList
数据结构
兴科Sinco4 小时前
[leetcode 1]给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数[力扣]
python·算法·leetcode
沐怡旸4 小时前
【算法--链表】138.随机链表的复制--通俗讲解
算法·面试
anlogic4 小时前
Java基础 9.10
java·开发语言·算法
薛定谔的算法4 小时前
JavaScript单链表实现详解:从基础到实践
数据结构·算法·leetcode
CoovallyAIHub4 小时前
CostFilter-AD:用“匹配代价过滤”刷新工业质检异常检测新高度! (附论文和源码)
深度学习·算法·计算机视觉