当前位置:网站首页>Leetcode.24 两两交换链表中的节点(递归)
Leetcode.24 两两交换链表中的节点(递归)
2022-07-30 02:24:00 【Curz酥】
题目链接:https://leetcode.cn/problems/swap-nodes-in-pairs/
题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:输入:head = []
输出:[]
示例 3:输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
解析
这里用递归法进行解题。
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 == NULL or head->next == NULL) return head;
ListNode* newHead = head->next;
head->next = swapPairs(newHead->next);
newHead->next = head;
return newHead;
}
};边栏推荐
猜你喜欢
随机推荐
Typora transparent background image
[深入研究4G/5G/6G专题-45]: 5G Link Adaption链路自适应-1-总体架构
Is it difficult for AI to land?Cloud native helps enterprises quickly apply machine learning MLOps
固体火箭发动机三维装药逆向内弹道计算
LeetCode Question of the Day (874. Walking Robot Simulation)
consul 操作
el-table sum total
What to test for app testing
go grpc custom interceptor
05.script_setup中的私有属性
【C语言刷LeetCode】2295. 替换数组中的元素(M)
Tibetan Mapping
共享内存-内存映射-共享文件对象
Tcp ip
综合设计一个OPPO页面--返回顶部使用--使用链接的锚点a+id
一个塑料瓶的海洋“奇幻漂流”
About offline use of SAP Fiori apps
go 双向流模式
Using ESP32 construct a ZIGBEE network adapter
JS develops 3D modeling software










