链表第一个节点删除问题!!!尝试了各种方法仍无效!求指点!!!
c语言吧
全部回复
仅看楼主
level 1
用VC编的程序,图书馆管理系统,里面有一个子程序要删除书籍信息,按照图书的编号删除建立的结构体为struct book/*书籍信息*/
{int number;int condition;/*书籍状态:在馆为1,不在为0*/
char name[200];/*书名*/
char author[100]; /*作者*/
char publish[200];/*出版社*/
long year; /*出版年份*/
char ISBN[30];/*ISBN码*/
float price;/*书籍价格*/
int n; /*借出次数*/
char user[30];
struct book *next;
};
typedef struct book BOOK;
删除的子程序为
/*删除书籍*/
BOOK *DeleteBook(BOOK *head)
{int i=0;
int nodeNum;
char c;
do{
printf("请输入要删除的图书编号:\n");
   scanf("%d",&nodeNum);   
head=DeleteNode(head,nodeNum);
   printf("是否继续?(y/n):");
   scanf(" %c",&c);   
}while(c=='y'||c=='Y');
   return head;
}
BOOK *DeleteNode(BOOK *head, int nodeNum)
{   
BOOK *p=head,*pr=head;
   if(head==NULL)   
{
printf("No linked table!");
return (head);
}
while (head->number==nodeNum&&head->next!=NULL)
   {
head=head->next;
free(p);
free(pr);
p=pr=NULL;
return head;
   }
while (nodeNum!=p->number&&p->next!=NULL)
   { pr=p;   
p=p->next;
   }   
if (nodeNum==p->number)
{
if(p==head)
{
head=p->next;
}   
else     
{
   pr->next=p->next;
   }
free(p);
   }
else
   {
printf("未找到该书籍!");
   }  
return head;
}
主要就是删除第一个节点的问题,后面的节点都没问题,删除时只要输入的是删除第一本程序就直接死掉。如果把free(p);free(pr);删掉的话可以正常运行,但删不掉第一个节点。求大神指点,在线等解答
2011年06月14日 11点06分 1
level 9
[汗]没见过这样使用链表来删除的。。。
2011年06月14日 12点06分 2
level 1
额,书上有个例题就是这种格式的,就照搬过来了,有木有改进方法啊?我不介意修改子程序的
2011年06月14日 12点06分 3
level 14
删除第一个,直接修改头结点指针。
p = head;
head = head->next;
free(p);
return head;
2011年06月14日 12点06分 4
level 1
BOOK *DeleteNode(BOOK *head, int nodeNum)
{
BOOK *p=head,*pr=head;
   if(head==NULL)   
{
printf("No linked table!");
return (head);
}
while (head->number==nodeNum&&head->next!=NULL)
   {
p = head;  
head = head->next;
   free(p);   
return head;
   }
前半部修改成这样了,运行时删除第一本后打印删除后的结果时就会程序终止运行
2011年06月14日 12点06分 5
level 14
[瞌睡]放在循环中没意义,那段也仅是删除头节点。而且你有使用函数的返回值吗?
2011年06月14日 12点06分 6
level 1
把第一个while改成if这样还是木有什么效果额,还有你说的函数返回值是哪个函数的返回值啊?怎么用?
2011年06月14日 13点06分 7
level 14
你写的DeleteNode这函数的返回值,如果删除的是第一个结点,那么头指针就不再是原来的值,要用到返回的新值。head=DeleteNode(...);
2011年06月14日 13点06分 8
level 1
用了啊,在一楼里有的
BOOK *DeleteBook(BOOK *head)
{ int i=0;
int nodeNum;
char c;
do{
printf("请输入要删除的图书编号:\n");
   scanf("%d",&nodeNum);   
head=DeleteNode(head,nodeNum);
   printf("是否继续?(y/n):");
   scanf(" %c",&c);   
}while(c=='y'||c=='Y');
   return head;
}
是这样用的吧?
2011年06月14日 13点06分 9
level 14
你在DeleteBook中修改的只是一个副本。main中的你有修改吗?
2011年06月14日 13点06分 10
1