//建立链表的算法
#include<stdio.h>
#include<malloc.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student{
long num;
float score;
struct student *next;
};
int n;
int main(){
struct student* creat();
struct student *p;
p = creat();
if(p!=NULL){
printf("一共%d条链表数据:\n",n);
do{
printf("%ld %f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
}
struct student *creat(){
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *)malloc(LEN);
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);
}
p2->next=NULL;
return(head);
}
算法思想:
首先有一个结构体,它除了自己有用的结点外还有一个指针结点用于指向下一个链表结点。
创建链表:首先调用函数malloc创建链表,而其长度就是sizeof(结构体),这样创建出来的链表返回值是void,因此要强制类型转换后将其赋值给指针型变量p1p2,而后进行键入值给p1对应的结点,再判断结点值是否为0,若不是则说明这是一个新的表项应该插入,再判断n的值,若是1则说明是第一个表项,对应的地址就给head。若不是1,那么将p1的值赋给p2的next结点。再重写创建链表并键入值后再循环。
输出链表:略