在线跪求C语言高手
- 提问者网友:嘚啵嘚啵
- 2021-01-06 11:48
- 五星知识达人网友:北方的南先生
- 2021-01-06 11:57
# include
# include
# define NULL 0
#include
# define LEN sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
int n;
struct student *creat(void) //建立链表的函数
{
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *) malloc(LEN);
//这里不应该加逗号scanf("%ld,%f",&(p1->num),&(p1->score));
scanf("%ld%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1)
head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *) malloc(LEN);
//这里不应该加逗号scanf("%ld,%f",&(p1->num),&(p1->score));
scanf("%ld%f",&p1->num,&p1->score);
}
p2->next=NULL;
return (head);
}
void print(struct student *head) //输出链表的函数
{
struct student *p;
printf("
Now,These %d records are:
",n); p=head;
if(head!=NULL)
do
{
//printf("%ld %5.1f
",&p->num,&p->score); 有问题
printf("%ld %5.1f
",p->num,p->score); p=p->next;
}while(p!=NULL);
}
struct student *del(struct student *head,long num) //对链表的删除操作的函数
{
struct student *p1,*p2;
if(head==NULL)
{
printf("
list null!
"); goto end;
}
p1=head;
while(num!=p1->num && p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(num==p1->num)
{
if(p1==head)
head=p1->next;
//还应该销毁头节点,free(p1);
else
p2->next=p1->next;
//还应该销毁此节点, free(); free(p1);
printf("delete:%ld
",num); n=n-1;
}
else
printf("%ld not been found!
",num);end:;
return (head);
}
struct student *insert(struct student *head,struct student *stud) //插入链表的函数
{
struct student *p0,*p1,*p2;
p1=head;
p0=stud;
if(head==NULL)
{
head=p0;
p0->next=NULL;
}
else
{
while ((p0->num>p1->num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p0->num<=p1->num)
{
if(head==p1)
head=p0;
else p2->next=p0;
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
n+=1;
}
return (head);
}
int main() //主函数,包括建立一个链表,删除一个节点,再插入一个节点,每个操作之后都有一个输出链表的操作
{
struct student *head,stu;
long del_num;
printf("input records:
"); head=creat();
print(head);
printf("
input the delete number:");
scanf("%ld,%f",&del_num);
head=del(head,del_num);
print(head);
printf("
input the inserted record:"); //这里不应该加逗号scanf("%ld,%f",&stu.num,&stu.score);
scanf("%ld%f",&stu.num,&stu.score);
head=insert(head,&stu);
print(head);
system("pause");
return 0;
}
- 1楼网友:玩世
- 2021-01-06 14:39
- 2楼网友:人類模型
- 2021-01-06 13:27