公司笔试或面试常考这一点。
递归解法如下:
node* reverse(node * head)
{
if(head==NULL || head->next==NULL)
return head;
node* tail= head->next;
node* newHead= reverse(head->next);
tail->next=head;
head->next=NULL;
return newHead;
}
非递归三指针解法如下:
node* reverse(node * head)
{
if(head==NULL || head->next==NULL)
return head;
node *p1, *p2, *p3;
p1=head;
p2=head->next;
head->next=NULL;
while ((p3=p2->next) != NULL)
{
p2->next=p1;
p1=p2;
p2=p3;
}
p2->next=p1;
head=p2;
return head;
}