题目描述:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
实现链表的翻转,而且题目提示可以尝试迭代和递归两种方法。
算法思路参考:http://www.cnblogs.com/grandyang/p/4478820.html
迭代的方法比较容易想到,不过指针的操作略微复杂需要比较小心。先定义result节点,将其置于head节点之前,然后每次都把head之后的节点插入到result之后,直到head->next为空,即head为最后一个节点,迭代结束。由于需要保证将head->next移动至result之后,那么head->next显然不能为空,所以节点数为0或者1的情况需要预先排除。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL) return NULL;
else if(head->next==NULL) return head;
ListNode* result=new ListNode(0);
result->next=head;
while(head->next!=NULL)
{
ListNode* p=head->next;
ListNode* q=head->next->next;
ListNode* temp=result->next;
result->next=p;
p->next=temp;
head->next=q;
}
return result->next;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL) return NULL;
else if(head->next==NULL) return head;
else if(head->next!=NULL)
{
ListNode* p=head;
head=reverseList(p->next);
p->next->next=p;
p->next=NULL;
}
return head;
}
};