#leetcode#206. Reverse Linked List
2016-04-19 23:09
274 查看
单链表翻转(递归和迭代两种)
迭代
/**
* 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 || head->next==NULL)
return head;
ListNode Result(0);
ListNode *p=head;
while(p)
{
ListNode *q=p->next;
p->next=Result.next;
Result.next=p;
p=q;
}
return Result.next;
}
};
递归
/**
* 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 *p=head->next;
ListNode *n=reverseList(p);
head->next=NULL;
p->next=head;
return n;
}
};
迭代
/**
* 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 || head->next==NULL)
return head;
ListNode Result(0);
ListNode *p=head;
while(p)
{
ListNode *q=p->next;
p->next=Result.next;
Result.next=p;
p=q;
}
return Result.next;
}
};
递归
/**
* 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 *p=head->next;
ListNode *n=reverseList(p);
head->next=NULL;
p->next=head;
return n;
}
};
相关文章推荐
- 搜索与机器学习
- RestFul API初识
- Django进阶(一) 数据库的ORM操作之一对多
- CSS滤镜
- Android的性能优化
- Swift中文教程(六)函数
- 双向循环链表(创建·插入·删除·遍历)
- Python Mixin编程机制
- Android 编码规范
- Java Set简单用法
- 巩固C语言(十二)----文件加解密
- Sharepoint 轻量化应用之初试面谈表单制作!
- DDD 领域驱动设计-如何完善 Domain Model(领域模型)?
- centos 6 yum源记录,离线下载rpm包的办法
- 数论基础2
- 从谷歌宕机事件认识互联网工作原理
- Linux驱动开发-14、串行设备驱动模型
- spring事务管理几种方式(转)
- css3 之 border-sizing
- andriod bluetooth gatt 详细讲解