leetcode之Swap Nodes in Pairs
来源:互联网 发布:apache性能测试工具ab 编辑:程序博客网 时间:2024/06/13 10:17
看到这道题目竟然也可以使用递归,我的第一反应是很惊奇,此前都是用到了好几个指针,相互指来指去,稍不留意就会出错,很是麻烦。用到了递归之后就会变得很容易。这里
给出递归的代码,代码量也一下子少了不少,当然牺牲了时间复杂度
(1)C语言实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
struct ListNode* n = head->next;
head->next = swapPairs(head->next->next);
n->next = head;
return n;
}
(2)C++实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* p = head->next;
head->next = swapPairs(head->next->next);
p->next = head;
return p;
}
};
(3)java实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}
- leetcode之Swap Nodes in Pairs
- LeetCode 之 Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- 【LeetCode】之Swap Nodes in Pairs
- 【Leetcode】之Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- LeetCode之24----Swap Nodes in Pairs
- Leetcode 之 Swap Nodes in Pairs
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- 数据持久化方式
- mybatis学习笔记二mybatis结合spring mvc实现(用户登录,数据查询)
- AndroidManifest注解
- rpm 安装指令全 yum 安装 卸载命令
- eclipse点击一个变量名不会出现同名的变量 的高亮提示
- leetcode之Swap Nodes in Pairs
- C# out和ref参数修饰符
- 设计模式与重构是一种追求
- 图像图形的各种变换
- 56 RAII实现智能指针
- 微信精选——上拉加载
- Android 自定义对话框dialog
- 课程练习一 Problem F id: 1005
- C/C++访问Lua中table元素方法总结