链表递归-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;//嵌套的函数全部有了返回值  这是最终的结果  ①的返回值
}
相关推荐
1104.北光c°3 分钟前
滑动窗口HotKey探测机制:让你的缓存TTL更智能
java·开发语言·笔记·程序人生·算法·滑动窗口·hotkey
仰泳的熊猫4 小时前
题目2570:蓝桥杯2020年第十一届省赛真题-成绩分析
数据结构·c++·算法·蓝桥杯
无极低码7 小时前
ecGlypher新手安装分步指南(标准化流程)
人工智能·算法·自然语言处理·大模型·rag
软件算法开发8 小时前
基于海象优化算法的LSTM网络模型(WOA-LSTM)的一维时间序列预测matlab仿真
算法·matlab·lstm·一维时间序列预测·woa-lstm·海象优化
Thera7778 小时前
C++ 高性能时间轮定时器:从单例设计到 Linux timerfd 深度优化
linux·开发语言·c++
罗超驿8 小时前
独立实现双向链表_LinkedList
java·数据结构·链表·linkedlist
superior tigre8 小时前
22 括号生成
算法·深度优先
君义_noip9 小时前
信息学奥赛一本通 1952:【10NOIP普及组】三国游戏 | 洛谷 P1199 [NOIP 2010 普及组] 三国游戏
c++·信息学奥赛·csp-s
努力也学不会java9 小时前
【缓存算法】一篇文章带你彻底搞懂面试高频题LRU/LFU
java·数据结构·人工智能·算法·缓存·面试