c中的链表add_before和add_after函数
在创建链表以便在元素之后和元素之前添加一些数据时,我使用了从教程中学习到的以下功能:c中的链表add_before和add_after函数,c,pointers,linked-list,C,Pointers,Linked List,在创建链表以便在元素之后和元素之前添加一些数据时,我使用了从教程中学习到的以下功能: struct node *addafter(struct node *start,int data,int item) { struct node *tmp,*p; p=start; while(p!=NULL) { if(p->info==item) { tmp=(struct node *)malloc(sizeo
struct node *addafter(struct node *start,int data,int item)
{
struct node *tmp,*p;
p=start;
while(p!=NULL)
{
if(p->info==item)
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=p->link;
p->link=tmp;
return start;
}
p=p->link;
}
printf("Item Not Found:\n");
return start;
}
struct node *addbefore(struct node *start,int data,int item)
{
struct node *tmp,*p;
if(item==start->info)
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->link=start->link;
tmp->info=data;
start->link=tmp;
return start;
}
p=start;
while(p->link!=NULL)
{
while(p->link->info==item)
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=p->link;
p->link=tmp;
return start;
}
p=p->link;
}
printf("Item Not Found:\n");
return start;
}
我的疑问在于addafter函数为什么停止条件是p=NULL,如果是addbefore函数,则为其p->link=空?请任何人解释一下 要将节点添加到单个链接列表,必须有指向该节点的指针,然后才能添加节点 因此,如果要在第3个节点之后添加节点,则需要指向第3个节点的指针。 如果要在第3个节点之前添加节点,则需要指向第2个节点的指针 所以,在之前和之后需要什么指针是不同的。因此,对于after情况,当前指针(
p
在您的情况下)需要指向项匹配的节点,而在before情况下,当前指针需要指向项匹配的节点之前的节点
您还可以通过维护prev指针,使用while(p!=NULL)
重写addbefore
案例
struct node *addbefore(struct node *start,int data,int item)
{
struct node *tmp,*p,*prv;
if(item==start->info)
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->link=start->link;
tmp->info=data;
start->link=tmp;
return start;
}
p = start->link;
prv = start;
while(p != NULL)
{
if(p->info==item)
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=p;
prv->link=tmp;
return start;
}
prv = p;
p=p->link;
}
printf("Item Not Found:\n");
return start;
}
写before代码的任何一种方法都可以。自己画一个关于它如何工作的图表将帮助您理解。简单的解释:在
中,而循环addafter
将访问p->info
,因此请检查p
验证。在addbefore
的while
循环中,将访问p->link
,因此请检查p->link
验证。while(p->link->info==item)
错误。当
时,如果
不是,则应为,因为控件在该块末尾返回(返回开始;
)。