22.leetcode题目206: Reverse Linked List
2016-03-16 21:04
239 查看
题目:
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
分析:
翻转链表。
根据提示:方法一,依次翻转
class Solution {
public:
ListNode* reverseList(ListNode* head) {
<span style="color:#006600;"> //reversed iteratively</span><span style="color:#ffff00;">
</span> if(head==NULL){
return head;
}
ListNode* res=head;
ListNode* p=res->next;
res->next=NULL;
while(p!=NULL){
ListNode* q=p->next;
p->next=res;
res=p;
p=q;
}
return res;
}
};方法二,递归调用
class Solution {
public:
ListNode* reverseList(ListNode* head) {
<span style="color:#006600;">//reversed recursively</span>
if(head==NULL||head->next==NULL){
return head;
}
ListNode* p=head->next;
ListNode* res=reverseList(p);
head->next=NULL;
p->next=head;
return res;
}
};
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
分析:
翻转链表。
根据提示:方法一,依次翻转
class Solution {
public:
ListNode* reverseList(ListNode* head) {
<span style="color:#006600;"> //reversed iteratively</span><span style="color:#ffff00;">
</span> if(head==NULL){
return head;
}
ListNode* res=head;
ListNode* p=res->next;
res->next=NULL;
while(p!=NULL){
ListNode* q=p->next;
p->next=res;
res=p;
p=q;
}
return res;
}
};方法二,递归调用
class Solution {
public:
ListNode* reverseList(ListNode* head) {
<span style="color:#006600;">//reversed recursively</span>
if(head==NULL||head->next==NULL){
return head;
}
ListNode* p=head->next;
ListNode* res=reverseList(p);
head->next=NULL;
p->next=head;
return res;
}
};
相关文章推荐
- XCode中遇到not available in automatic reference counting mode 报错
- Http Response Code[整理]
- 动态规划
- Bootstr 导航
- 牛顿法和线搜索&信任域
- 剑指offer 二叉搜索树后续遍历序列 判断
- lightoj 1213 - Fantasy of a Summation 【数学计数】
- Uva 11395 Sigma Function (因子和)
- 胜利大逃亡(续)
- HDU 2412 Party at Hali-Bula(树状DP)
- Android设计模式之23种设计模式一览
- 杨辉三角
- AngularJS 简介
- 作业二:在github上过程
- 0316-复利计算更新
- [转载] C++ string, const char*, char* 之间互相转换
- 胜利大逃亡(续)
- golang 学习笔记
- sql经典题
- Oulipo (HDU_1686) KMP