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)
{
ListNode *dummy=NULL;
ListNode *p=head;
while(p)
{
ListNode *t=p->next;
p->next=dummy;
dummy=p;
p=t;
}
return dummy;
}
};
第二种方法:递归法
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if (!head || !(head -> next))
return head;
ListNode* node = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return node;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
return reverse(head,NULL);
}
ListNode * reverse(ListNode *head,ListNode *newNode)
{
if(head==NULL)
return newNode;
ListNode *next=head->next;
head->next=newNode;
return reverse(next,head);
}
};