方法一:双指针
部分代码:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* temp;
ListNode* cur=head;
ListNode* pre=NULL;
while(cur)//等同于cur!=NULL
{
temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
};
方法二:递归法
部分代码:
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur)
{
if(cur==NULL) return pre;
ListNode* temp;
temp=cur->next;
cur->next=pre;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head)
{
return reverse(NULL,head);
}
};