链表的知识,定义了一个结构体数组,想删除链表中的第一个结构体元素,下面的函数怎么不行??

鬼鬼先生 2013-04-10 12:34:48
void Delete(struct student *head)
{
system("cls");
int exit=0;
char s[5];
printf("输入要删除学生的学号:(如果删除所有学生请输入0000)\n学号:");
scanf("%s",s);
while(!exit){
if(strlen(s)!=4){
printf("输入非法:学号必须是4位,请重新输入!\n");
scanf("%s",s);}
else
exit=1;
}
struct student *p1,*p2;
if(head==NULL)
{
printf("\nthe list is null!\n");
}
p1=head;
while(strcmp(p1->ID,s)!=0&&p1->next!=NULL){
p2=p1;
p1=p1->next;
}
if(strcmp(p1->ID,s)==0){
if(p1==head)
head=p1->next;
else
p2->next=p1->next;
free(p1);
iTotal--;
printf("%s的学生成功删除\n",s);
}
else
printf("没有找到学号为 %s 的学生,请确认学号输入是否正确!\n",s);
printf("press any key to continue ");
getch();
}
...全文
212 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
鬼鬼先生 2013-04-11
  • 打赏
  • 举报
回复
谢谢了,非常有用
AndyStevens 2013-04-11
  • 打赏
  • 举报
回复
p1=p2=(struct student *)malloc(sizeof(struct student)); 你这句等同于: p2 = (struct student *)malloc(sizeof(struct student)); p1 = p2; 然后, 因为p1和p2指向同一块内存,所以之后对p2的初始化覆盖了之前对p1的赋值, p1->Next= p2->Next = NULL; 所以print里 只循环一次,输出的是P2的值。。。
鬼鬼先生 2013-04-11
  • 打赏
  • 举报
回复
#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<malloc.h> #include<string.h> struct student *creat(); void print(struct student *head); struct student { char ID[5]; char name[20]; float score; struct student *next; }*list; struct student *creat() { struct student *head,*p1,*p2; head=NULL; p1=p2=(struct student *)malloc(sizeof(struct student)); head=p1; strcpy(p1->ID,"0001");strcpy(p1->name,"liwei");p1->score=88.88; p1->next=p2; strcpy(p2->ID,"0002");strcpy(p2->name,"wangba");p2->score=88.99; p2->next=NULL; return(head); } void print(struct student *head) { printf("所有学生信息:\n"); struct student *p; int i=1; p=head; while(p!=NULL){ printf("%d:%s,%s,%.2f\n",i,p->ID,p->name,p->score); p=p->next; i++; } } void main() { list=creat(); print(list); } 为什么我创建两个变量p1,p2,只能输出一个,求大神指导!!!
鬼鬼先生 2013-04-11
  • 打赏
  • 举报
回复
谢谢了,很有用,
cy2015yc 2013-04-10
  • 打赏
  • 举报
回复
head=p1->next; 因为参数是指传递,所以这一句对实参没有影响。 可以把函数参数修改为引用传递 struct student *&head 或者传入head的地址 struct student** head

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧