标签:
Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
使用迭代和递归实现单链表的反转。
迭代的方法之间在剑指offer上面见到过,使用三个指针,需要注意一点的是指针的初始化,对第一个指针初始化为NULL,第二个指针初始化为head,第三个指针初始化为NULL,不能将第一个指针初始化成head,否则最后反转后的链表的尾端指向的不是NULL。
runtime:12ms
/**
* 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 * first=NULL;
ListNode * second=head;
ListNode * third=NULL;
while(second)
{
third=second->next;
second->next=first;
first=second;
second=third;
}
return first;
}
};递归的解法,递归的解法可以这么思考,对于一个节点node,假设它后面的剩余链表已经是反转的了,此时该如何处理?递归结束的终止条件是什么?之前把递归结束的终止条件思考复杂了,但是还是把题目解出来了。
当链表元素为空时返回NULL,或者链表元素只有一个时返回本身这两点很明显,但是最开始还考虑了剩下两个节点时的情况,如下:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
if(head->next->next==NULL)
{
ListNode * first=head;
ListNode * second=head->next;
head->next=NULL;
second->next=head;
return second;
}
ListNode * tmp=head->next;
ListNode *res=reverseList(head->next);
tmp->next=head;
head->next=NULL;
return res;
}最后发现解法二种不必把含有两种节点的情况单独拿出来讨论,它已经包含在处理流程中了,但是分析时可以分析到含有两种节点的情况,这样问题就会更清晰明显,以后处理递归问题需要注意到这一点,不要写出冗余的代码。
runtime:8ms
ListNode* reverseList(ListNode* head)
{
if(head==NULL||head->next==NULL)
return head;
ListNode * nextNode=head->next;
ListNode * res=reverseList(head->next);
nextNode->next=head;
head->next=NULL;
return res;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode206:Reverse Linked List
标签:
原文地址:http://blog.csdn.net/u012501459/article/details/47144951