1.直接手动输入数据
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define size sizeof(struct student)
struct student{//结构体声明
long num;
char name[20];
int grade;
struct student *next;
};
struct student *creat(void){//创建链表函数
struct student *p1,*p2,*head;
int n=0;
head=NULL;
p1=p2=(struct student*)malloc(size);
scanf("%ld %s %d",&p1->num,p1->name,&p1->grade);
while(p1->num!=0){
n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student*)malloc(size);
scanf("%ld %s %d",&p1->num,p1->name,&p1->grade);
}
p2->next=NULL;
return head;
}
struct student *del(struct student *head,long num,int n){//删除链表函数
struct student *p1,*p2;
p1=head;
if(head==NULL) printf("list null\n");
while(p1->num!=num&&p1->next){
p2=p1;
p1=p1->next;
}
if(p1->num==num){
if(p1==head) head=p1->next;
else p2->next=p1->next;
n=n-1;
printf("%ld is deleted.\n",num);
}
else printf("can't found %ld in the list.\n",num);
return (head);
}
struct student *add(struct student *head,struct student *stu,int n){//插入链表函数
struct student *p0,*p1,*p2;
p1=head;
p0=stu;
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(p1==head) head=p0;
else p2->next=p0;
p0->next=p1;
}
else{ //表尾
p1->next=p0;
p0->next=NULL;
}
printf("%ld has been inserted:\n",stu->num);
n+=1;
}
return (head);
}
void print(struct student *head){
struct student *p=head;
while(p!=NULL){
printf("%ld %s %d\n",p->num,p->name,p->grade);
p=p->next;
}
}
int main(){//主函数
struct student *head,*pt,*pt1,*pt2,*stu;
head=creat();
pt=head;
print(pt);
pt1=head;
pt1=del(pt1,1002,4);
print(pt1);
pt2=head;
stu=(struct student *)malloc(size);
printf("Input inserted student here:\n");
scanf("%ld %s %d",&stu->num,stu->name,&stu->grade);
pt2=add(pt2,stu,4);
print(pt2);
return 0;
}
2.利用文件读入数据
其实就只有创建链表函数部分改动一下,其余部分不变。变动后代码如下:
//创建链表函数
struct student* creat(void) {
struct student* p1, * p2, * head;
int n = 0;
head = NULL;
p1 = p2 = (struct student*)malloc(size);
FILE *fp; //创建一个文件指针
fp=fopen("D:\\桌面\\成绩.txt","r");//以“r”只读形式打开文件
while((fp=fopen("D:\\桌面\\成绩.txt","r"))==NULL){//检查是否成功打开
printf("can't open this file\n");
exit(0);
}
fscanf(fp,"%ld %s %d", &p1->num, p1->name, &p1->grade);//从文件中读入信息
while (p1->num != 0) {
n = n + 1;
if (n == 1) head = p1;
else p2->next = p1;
p2 = p1;
p1 = (struct student*)malloc(size);
fscanf(fp,"%ld %s %d", &p1->num, p1->name, &p1->grade);//从文件中读入信息
}
fclose(fp);//关闭文件
p2->next = NULL;
return head;
}
第一篇文章,若有不妥,还请指出,我定虚心学习。