链表的概述:
一个节点包含两部分: 1、用户需要的实际数据。 2、下一个节点的地址。
我们可以设计一个这样的结构体:
struct student{
int num;
float score;
struct stuent * next; //next 是成员名,是指针类型,它指向下一个struct student 的地址
};
制作一个简单的链表:
处理动态链表所需的函数:
1、malloc函数:
void * maloc(unsigned int size); //分配一个长度为size 的连续空间
2、calloc函数:
void *calloc(unsigned n, unsigned size); // 分配 n 个长度为size的连续空间
3、free函数:
void free(void *p); //释放由 p 指向的动态存储区,使这部分内存能被其他变量使用,p是最近一次调用 calloc 或 malloc 函数时返回的值。
建立动态链表的方法:
代码部分:
#include<stdio.h>
#include<malloc.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student *creat(void);
struct student{
long num;
float score;
struct student *next;
};
struct student *creat(void){
int n=0;
struct student *head,*p1,*p2;
p1=p2=(struct student *)malloc(LEN); //有个 * 号是强制转换。用malloc函数开辟第一个节点。
scanf("%d,%f",&p1->num,&p1->score); //向 p1 指针指向的地址添加数据
head=NULL; // 先让头指针为空
while(p1->num!=0) //约定学号不为0
{
n=n+1;
if(n==1)
head=p1; //将 p1 指针 指向的地址赋给 head 图a
else
p2->next=p1; //p2->next 指向了新开辟的 p1 指向的新开辟的数据结构 图b
p2=p1; //将 p1 所指向的地址赋给 p2 图c
p1=(struct student *)malloc(LEN); // p1 再重新指向一个新开辟的地址 图a(2)
scanf("%d,%f",&p1->num,&p1->score); //向 p1 指向的这个地址输入数据, 也就是向新开辟的地址输入数据
}
p2->next=NULL; //最后赋予NULL;
return(head);
}
void main(){
struct student *head,*p;
head=creat();
p=head; //将head所指向的地址赋给p
if(head!=NULL)
while(p!=NULL)
{
printf("%d %f ",p->num,p->score);
p=p->next;
printf("\n");
}
}