// 静态链表
/*
链表中所有节点的数据在内存中的分布都是在编译时就确定,程序运行后不能再进行变更,因此这种链表又叫做"静态链表"
*/
#include <stdio.h>
struct book
{
int num;
float price;
struct book *next;
};
int main()
{
struct book x,y,z; // 定义三个结构体
struct book *head = NULL; // 链表头节点
struct book *p = NULL; // 临时结构体指针
x.num = 001;
x.price = 13.5f;
y.num = 002;
y.price = 26.5f;
z.num = 003;
z.price = 98.5f;
head = &x;
x.next = &y;
y.next = &z;
z.next = NULL;
p = head;
while (p != NULL)
{
printf("图书编号:%03d\t\t图书价格:%.2f\n",p->num,p->price);
p = p->next;
}
return 0;
}
// 动态链表
/*
在需要时才创建一个节点,并将该节点的地址添加到链表中,这种动态创建节点的链表叫做动态链表
*/
#include <stdio.h>
#include <stdlib.h> // 用到malloc函数,需要导入stdlib.h
typedef struct book
{
int num;
float price;
struct book *next;
}BOOK;
BOOK *head = NULL; // 头节点
void creat() // 此函数只能创建一个节点的链表
{
BOOK *p = NULL;
p = (BOOK *)malloc(sizeof(BOOK));
printf("请输入图书的编号:");
scanf("%d",&p->num);
printf("请输入图书的价格:");
scanf("%f",&p->price);
head = p; // 将头节点指向p
p->next = NULL; // p的尾节点为空,表示链表结束
}
int main()
{
creat();
return 0;
}