leetcode之Swap Nodes in Pairs
2016-04-05 12:08
501 查看
看到这道题目竟然也可以使用递归,我的第一反应是很惊奇,此前都是用到了好几个指针,相互指来指去,稍不留意就会出错,很是麻烦。用到了递归之后就会变得很容易。这里
给出递归的代码,代码量也一下子少了不少,当然牺牲了时间复杂度
(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;
}
}
给出递归的代码,代码量也一下子少了不少,当然牺牲了时间复杂度
(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;
}
}
相关文章推荐
- windows安装完nodejs,cmd输入npm没反应,npm install 没反应
- 基于nodejs的前端开发环境
- LeetCode之旅(21)-Swap Nodes in Pairs
- LeetCode之旅(21)-Swap Nodes in Pairs
- LeetCode之旅(21)-Swap Nodes in Pairs
- Node.js + Web Socket 打造即时聊天程序嗨聊
- Node.js服务器
- nodejs v8引擎c++编译版本升级教程
- 【z13区】nodejs原生态模块,写个聊天室
- 揭秘DOM中data和nodeValue属性同步改变那些事
- 24. Swap Nodes in Pairs
- Nodejs积累
- Nodejs超方便更新方式
- (四)Electron 把boostrap控件当做桌面控件用
- 使用nvm让不同版本的Node.js共存
- ECMAScript 2015 (ES6) in Node.js(译)
- nodejs群聊和私聊
- 24. Swap Nodes in Pairs
- Node.js其他模块
- 深入浅出NodeJS笔记(五)---- Promise的序列执行