#include
#include
struct book
{
int num;
char pub[50]
int many;
struct book *next;
};
struct book *creat()
{
struct book *p1,*p2,*head=NULL;
p1=p2=(struct book *)malloc(sizeof(struct book ));
scanf("%d%s%d",&p1->num,p1->pub,&p1->many);
while(p1->num!=0)
{ if(head==NULL)
head=p1;
else
{
p2=p1->next;
p2=p1;
}
p1=(struct book *)malloc(sizeof(struct book));
scanf("%d%s%d",&p1->num,p1->pub,&p1->many);
}
p1->next=NULL;
free(p1);
return head;
}
struct book *del(struct book *head, int num )
{
struct book *p1,*p2=NULL;
if(head==NULL)
printf("该链表为空\n");
else
{
p1=head;
while((p1->num!=num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p1->num==num)
{
if(p1==head)
head=p1->next;
else
p2->next=p1->next;
free(p1);
printf("该结点已删除\n");
}
else
printf("不存在该结点\n");
}
return head;
}
int howmany(struct book *head)
{
struct book *p1;
int a=0;
char b[100]={"清华大学出版社"};
if(head==NULL)
printf("改链表为空\n");
else
{
p1=head;
while(p1->num!=NULL)
if(p1->pub==b)
a=a+p1->many;
}
return a;
}
void list (struct book *head)
{
struct book *p;
if(head==NULL)
printf("链表为空\n");
else
{
printf("链表信息如下:\n");
p=head;
while(p!=NULL)
{
printf("%d%s%d",p->num,p->pub,p->many);
p=p->next;
}
}
}
int main()
{
struct book *head,*head1;
int m,n;
scanf("%d",&m);
head=creat();
printf("删除后的链表为\n");
head1=del(head,m);
n=howmany(head);
printf("%d",n);
list(head);
return 0;
}
creat函数里有问题p2=p1->next;改为p2->next=p1;
你的链表创建的时候有问题,根本没有把后面创建的结点接上去,所以导致只有输入一个数的时候才会删除正确
#include<stdio.h>
#include<stdlib.h>
struct book
{
int num;
char pub[50];
int many;
struct book *next;
};
struct book *creat()
{
struct book *p1,*p2,*head=NULL;
p1=p2=(struct book *)malloc(sizeof(struct book ));
p1->next = NULL;
scanf("%d%s%d",&p1->num,p1->pub,&p1->many);
while(p1->num!=0)
{
if(head==NULL)
head=p1;
else
{
p2->next=p1;
p2=p1;
}
p1=(struct book *)malloc(sizeof(struct book));
scanf("%d%s%d",&p1->num,p1->pub,&p1->many);
}
p1->next=NULL;
free(p1);
return head;
}
struct book *del(struct book *head, int num )
{
struct book *p1,*p2=NULL;
if(head==NULL)
printf("该链表为空\n");
else
{
p1=head;
while((p1->num!=num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p1->num==num)
{
if(p1==head)
head=p1->next;
else
p2->next=p1->next;
free(p1);
printf("该结点已删除\n");
}
else
printf("不存在该结点\n");
}
return head;
}
int howmany(struct book *head)
{
struct book *p1;
int a=0;
char b[100]={"清华大学出版社"};
if(head==NULL)
printf("改链表为空\n");
else
{
p1=head;
while(p1->num!=NULL)
if(p1->pub==b)
a=a+p1->many;
}
return a;
}
void list (struct book *head)
{
struct book *p;
if(head==NULL)
printf("链表为空\n");
else
{
printf("链表信息如下:\n");
p=head;
while(p!=NULL)
{
printf("%d%s%d",p->num,p->pub,p->many);
p=p->next;
}
}
}
int main()
{
struct book *head,*head1;
int m,n;
scanf("%d",&m);
head=creat();
printf("删除后的链表为\n");
head1=del(head,m);
n=howmany(head);
printf("%d",n);
list(head);
return 0;
}
p1=p2=(struct book *)malloc(sizeof(struct book ));
这里您确定不会出错吗。。。