链表递归-leetcode两两交换相邻链表中的结点

两两交换相邻链表中的结点

题目:

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例1

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

示例 2:

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

示例 3:

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

题解:

迭代

设置一个虚拟头结点,第一次设置为first结点 后面的连续两个结点设为second和third

c++ 复制代码
/**
 * 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*dummyHead=new ListNode(0,head);
        ListNode*first=dummyHead;
        while(first->next!=nullptr&&first->next->next!=nullptr)
        {
            ListNode*third=first->next->next;
            ListNode*second=first->next;
            second->next=third->next;  //二号结点连接三号节点的下一个即四号节点地址
            first->next=third; //一号结点连接三号节点
            third->next=second;  //三号结点连接二号节点
            first=first->next->next;  //一号结点向后移动两步
            }
        return dummyHead->next;
    }
};

递归法

c++ 复制代码
/**
 * 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||head->next==nullptr)
        {
            return head;
        }
        ListNode *newhead=head->next;
        head->next=swapPairs(newhead->next);
        newhead->next=head;
        return newhead;
    }
};

递归法展开:(以五个结点的链表为例)

c++ 复制代码
swapPairs(ListNode* head) {//①
    //第一层递归
    newhead =head->next;
    head->next=swapPairs(newhead->next);//② head->next=newhead->next->next
          //第二层函数递归
         {newhead=head->next;
          head->next=swapPairs(newhead->head); //③ head->next=newhead->next 当前函数下的head和newhead
                  //第三层递归 直接有了返回值
                  {return head;//这里的head是上面函数的newhead->head  是swapPairs(newhead->head)函数的返回值(③)  赋值给上一层的head->next
                  }
          newhead->next=head;
          return newhead;  //是函数②的返回值
         }
    newhead->next= head;
	return newhead;//嵌套的函数全部有了返回值  这是最终的结果  ①的返回值
}
相关推荐
颜酱几秒前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_7369191013 分钟前
C++代码风格检查工具
开发语言·c++·算法
yugi98783815 分钟前
基于MATLAB强化学习的单智能体与多智能体路径规划算法
算法·matlab
DuHz34 分钟前
超宽带脉冲无线电(Ultra Wideband Impulse Radio, UWB)简介
论文阅读·算法·汽车·信息与通信·信号处理
Polaris北极星少女1 小时前
TRSV优化2
算法
代码游侠2 小时前
C语言核心概念复习——网络协议与TCP/IP
linux·运维·服务器·网络·算法
2301_763472462 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
阿猿收手吧!2 小时前
【C++】std::promise原理与实战解析
c++
abluckyboy3 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异3 小时前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展