您的位置:首页 > 其它

不带头节点链表逆序的两种方法

2008-11-01 09:16 465 查看
公司笔试或面试常考这一点。

递归解法如下:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: