您的位置:首页 > 其它

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: