69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct student
{
long num;
char name[20];
char sex[10];
char year[200];
struct student *next;
};
struct student *create()
{
struct student *head, *p1, *p2;
int i, len;
head=NULL;
len=sizeof(struct student);
for(i=0; i<5; i++)
{
p1=(struct student *)malloc(len);
scanf("%ld %s %s %s",&p1->num, p1->name,p1->sex,p1->year);
if(i==0) head=p2=p1;
else
{
p2->next=p1;
p2=p1;
}
if(i==4) p2->next=NULL;
}
return head;
}
void display(struct student *head)
{
struct student *p1;
p1=head;
while(p1!=NULL)
{
printf("%ld\n%s\n%s\n%s\n",p1->num,p1->name,p1->sex,p1->year);
p1=p1->next;
}
}
int Delete(struct student **head,char a[200])
{
struct student *p1, *p2;
int flag=0;
p1=p2=*head;
while(p1!=NULL)
{
//这个不符合题目要求,下面是我修改的程序,写的不是很好,但是能够执行
if (strcmp(p1->year,a)==0)
{
flag = 1;
if (p1==*head)
{
*head=p1->next;
free(p1);
p1 = *head;
continue;
}
else
{
p2->next=p1->next;
free(p1);
p1 =p2;
}
}
p2=p1;
p1=p1->next;
}
return (flag==1)? 1 : 0;
}
void insert(struct student *head,char a[200])
{
struct student *p1,*q;
q=(struct student *)malloc(sizeof(struct student));
q->num = 180;//这儿缺少这个
strcpy(q->name,"aaa");
strcpy(q->sex,"male");
strcpy(q->year,a);
p1=head;
while(p1->next!=NULL)
{
p1=p1->next;
}
p1->next=q;
q->next=NULL;
}
int main( )
{
struct student *head;
char a[200];
head=create();
scanf("%s",a);
//Delete(&head,a);这个是多余的,因为你第一次已经删除了,所以下面的判断会成功,执行了insert函数。就会多出来一行
if (Delete(&head,a)!=1)
insert(head,a);
display(head);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct student
{
long num;
char name[20];
char sex[10];
char year[200];
struct student *next;
};
struct student *create()
{
struct student *head, *p1, *p2;
int i, len;
head=NULL;
len=sizeof(struct student);
for(i=0; i<5; i++)
{
p1=(struct student *)malloc(len);
scanf("%ld %s %s %s",&p1->num, p1->name,p1->sex,p1->year);
if(i==0) head=p2=p1;
else
{
p2->next=p1;
p2=p1;
}
if(i==4) p2->next=NULL;
}
return head;
}
void display(struct student *head)
{
struct student *p1;
p1=head;
while(p1!=NULL)
{
printf("%ld\n%s\n%s\n%s\n",p1->num,p1->name,p1->sex,p1->year);
p1=p1->next;
}
}
int Delete(struct student **head,char a[200])
{
struct student *p1, *p2;
p1=p2=*head;
while(p1!=NULL)
{
if (strcmp(p1->year,a)==0)
{
if (p1==*head)
*head=p1->next;
else
p2->next=p1->next;
free(p1);
return 1;
}
p2=p1;
p1=p1->next;
}
return 0;
}
void insert(struct student *head,char a[200])
{
struct student *p1,*q;
q=(struct student *)malloc(sizeof(struct student));
q->num = 180;//////////////////////////////这里
strcpy(q->name,"aaa");
strcpy(q->sex,"male");
strcpy(q->year,a);
p1=head;
while(p1->next!=NULL)
{
p1=p1->next;
}
p1->next=q;
q->next=NULL;
}
int main( )
{
struct student *head;
char a[200];
head=create();
scanf("%s",a);
//Delete(&head,a);//////////////////////////////这里
if (Delete(&head,a)!=1)
insert(head,a);
display(head);
return 0;
}