链表递归-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;//嵌套的函数全部有了返回值  这是最终的结果  ①的返回值
}
相关推荐
mit6.8242 小时前
[实现Rpc] 通信类抽象层 | function | using | 解耦合设计思想
c++·网络协议·rpc
laimaxgg3 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
尼尔森系4 小时前
排序与算法:希尔排序
c语言·算法·排序算法
AC使者4 小时前
A. C05.L08.贪心算法入门
算法·贪心算法
冠位观测者4 小时前
【Leetcode 每日一题】624. 数组列表中的最大距离
数据结构·算法·leetcode
sushang~5 小时前
leetcode203.移除链表元素
数据结构·链表
yadanuof5 小时前
leetcode hot100 滑动窗口&子串
算法·leetcode
可爱de艺艺5 小时前
Go入门之函数
算法
ox00805 小时前
C++ 设计模式-命令模式
c++·设计模式·命令模式
武乐乐~5 小时前
欢乐力扣:旋转图像
算法·leetcode·职场和发展