公司笔试或面试常考这一点。
递归解法如下:
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;
}
本文介绍了一种链表反转的方法,包括递归解法和非递归三指针解法。递归解法通过条件判断和函数自身调用实现链表反转;非递归解法则通过三个指针依次移动并调整节点的next指针来完成链表反转。
4493

被折叠的 条评论
为什么被折叠?



