LeetCode 刷题 -- 反转一个单链表
2015-11-13 16:07
267 查看
Reverse a singly linked list.
非递归法实现:
递归实现:
Youtube上有个视频对递归实现讲得不错:
https://www.youtube.com/watch?v=MRe3UsRadKw
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next == NULL)
{
return head;
}
ListNode* root = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return root;
}
};
非递归法实现:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head == NULL) { return NULL; } if(head->next == NULL) { return head; } ListNode *pre, *next; ListNode *it = head; pre = NULL; while(it) { next = it->next; it->next = pre; pre = it; it = next; } return pre; } };
递归实现:
Youtube上有个视频对递归实现讲得不错:
https://www.youtube.com/watch?v=MRe3UsRadKw
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next == NULL)
{
return head;
}
ListNode* root = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return root;
}
};
相关文章推荐
- 【经典面试题】给一组数,只有两个数只出现了一次,其他所有数都是成对出现的。怎么找出这两个数
- 在Ubuntu中安装软件遇到的问题
- ubuntu图下安装软件出现You might want to run 'apt-get -f install' to correct these解决
- myBatis
- HDOJ 3635 Dragon Balls(并查集)
- 【NVIDIA Jetson TK1】二,TK1开发板安装CUDA与opencv
- one代码框架学习
- WampServer下使用多端口访问的技巧
- 模拟器报Installation error: INSTALL_FAILED_CONTAINER_ERROR解决方法
- 手机自动化测试:Appium代码之Logger
- hdu 1255 覆盖的面积(线段树 面积交+离散化)
- freemarker常用的指令
- 理解MySQL——复制(Replication)
- FreeRTOS系列第2篇---FreeRTOS入门指南
- 验证码总是失效问题
- 适配器 QQ发送页面
- 微信支付(不得不吐槽腾讯这个坑货)
- 手机自动化测试:Appium源码分析之跟踪代码分析九
- javaEE之------Servlet通过web.xml传参数(生命周期)
- iOS中类单例方法的一种实现