一.链表的知识点
链表由数字域和指针域组成,
数字域存放如 num score 等内容
指针域存放下一个节点的首地址如next
链表由一个个节点组成,节点一般用结构体的形式如下
根节点(认为规定)有个计数器用于计整个链表的节点数
struct student
{
long num;
float score;
struct student *next;
} p;
二.静态链表代码
#include<stdio.h>
#include<stdlib.h>
struct student
{
long num;
float score;
struct student *next;
};
void main()
{
struct student a,b,c,*head;
a.num=10101;
a.score=56;
b.num=10102;
b.score=94;
c.num=10103;
c.score=99;
head=&a; //头指针指向链表中第一个元素的地址
a.next=&b;
b.next=&c;
do
{
printf("%ld %5.lf\n",head->num,head->score);
head=head->next;
}while(head !=NULL);
}
三.动态链表代码
#include<stdio.h>
#include <stdlib.h>
#include<malloc.h>
#define LEN sizeof (struct student)
struct student *creat(); //创建链表函数
void print(struct student *head); //打印链表
struct student
{
int num;
float score;
struct student *next;
};
int n;
struct student *creat()
{
struct student *head;
struct student *p1,*p2;
p1=p2=(struct student *)malloc(LEN);
printf("please input your num :");
scanf("%d",&p1->num);
printf("please input your score:");
scanf("%f",&p1->score);
head=NULL;
n=0;
while (p1->num !=0)
{
n++;
if(n==1)
{
head=p1;
}
else {
p2->next=p1;
}
p2=p1;
p1=(struct student *)malloc(LEN);
printf("please input your num;");
scanf("%d",&p1->num);
printf("please input your score;");
scanf("%f",&p1->score);
}
p2->next=NULL;
return head; //返回头节点
}
void print(struct student *head)
{
struct student *p;
printf("There are %d record student \n",n);
p=head;
if(head!=NULL)
{
do
{
printf("num is %d,score is %f",p->num,p->score);
p=p->next;
}while(p);
}
}
void main()
{
struct student *stu;
stu=creat();
print(stu);
printf("\n");
}