|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LEN sizeof(struct student)//student结构的大小
struct student *creat();//创建链表
struct stduent *del(struct student *head,int num);//del函数用于删除结点,*head即链表的头指针,num是要删除的结点num
void print(struct student *head);//打印链表,可以不写括号里面的参数,参数是写给程序员看的
struct student
{
int num;
float score;
struct student *next;
};
int n;//全局变量,用来记录放了多少个数据
int main(void)
{
struct student *stu,*p;
int n;
stu=creat();
p=stu;
print( p );
printf("please enter the number to delete:");
scanf("%d",&n);
print( del(p,n) );
system("pause");
return 0;
}
struct student *creat()
{
struct student *head;
struct student *p1,*p2;
p1=p2=(struct student *)malloc(LEN);//LEN是student结构的大小
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
head=NULL;
n=0;
while(p1->num)
{
n++;
if(1==n)
{
head=p1;
}
else
{
p2->next =p1;
}
p2=p1;
p1=(struct student *)malloc(LEN);
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
}
p2->next=NULL;
return head;
};
struct stduent *del(struct student *head,int num)
{
struct student *p1,*p2;
if(NULL==head)
{
printf("This list is NULL!\n\n");
goto END;
}
p1=head;
while(p1->num!=num&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(num=p1->num)
{
if(p1=head) //当删除的结点位于头结点时
{
head=p1->next;
}
else //一般情况
{
p2->next=p1->next;// A B C
}
printf("\nDelete the %d number succeed!\n");
n=n-1;//n作为一个全局变量,用来记录链表的数据量
}
else
{
printf("The number not been found!\n");
}
END:
return head;
};
void print(struct student *head)
{
struct student *p;
printf("There are %d records!\n\n",n);
p=head;
if(head)
{
do
{
printf("学号为%d的成绩是:%f\n",p->num,p->score);
p=p->next;
}while(p);
}
} |
|