Reverse a singly linked list.
Hint:
递归的方法:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题目要求将一个单链表逆置,可以用迭代的方法,也可以用递归的方法。
迭代的方法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL) return head;
ListNode* pre=NULL;
while(head->next!=NULL)
{
ListNode* tmp=head->next;
head->next=pre;
pre=head;
head=tmp;
}
head->next=pre;
return head;
}
};
递归的方法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode* pre=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return pre;
}
};