链表递归-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;//嵌套的函数全部有了返回值  这是最终的结果  ①的返回值
}
相关推荐
小字节,大梦想24 分钟前
【C++】二叉搜索树
数据结构·c++
吾名招财25 分钟前
yolov5-7.0模型DNN加载函数及参数详解(重要)
c++·人工智能·yolo·dnn
我是哈哈hh1 小时前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝
憧憬成为原神糕手1 小时前
c++_ 多态
开发语言·c++
郭二哈1 小时前
C++——模板进阶、继承
java·服务器·c++
Tisfy1 小时前
LeetCode 2187.完成旅途的最少时间:二分查找
算法·leetcode·二分查找·题解·二分
挥剑决浮云 -1 小时前
Linux 之 安装软件、GCC编译器、Linux 操作系统基础
linux·服务器·c语言·c++·经验分享·笔记
Mephisto.java1 小时前
【力扣 | SQL题 | 每日四题】力扣2082, 2084, 2072, 2112, 180
sql·算法·leetcode
robin_suli1 小时前
滑动窗口->dd爱框框
算法
丶Darling.1 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树