什么是链表?链表是结构体变量与结构体变量链接在一起,通过结构体指针链接在一起
如何动态创建链表:动态内存申请+模块化设计
这里插入的方法是头插法
1.创建链表
如何从结构体指针变成结构体变量我们需要动态内存申请
这句代码
struct Node* headnod = (struct Node*)malloc(sizeof(struct Node));
就是把结构体指针变成结构体变量
malloc是库函数,作用是分配所需内存空间
struct Node
{
int date;
struct Node* next;
};
//创建链表
struct Node* list()
{
struct Node* headnod = (struct Node*)malloc(sizeof(struct Node));
//head就变成了结构体变量
//变量使用前要初始化
headnod->date=1;//一般不初始化成1
headnod->next = NULL;
return headnod;
}
2.创建节点
//创建节点
//和我们创建链表相比多了一个数据域其他的创建链表都差不多
struct Node* createnode(int date)
{
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->date = date;
newnode->next = NULL;
return newnode;
3.插入节点
void insertnode(struct Node* headnod, int date)
{
//1.创建插入节点(因为我们已经写好了一个创建节点的函数直接调用就可以了)
struct Node* newnod = createnode(date);
newnod->next = headnod->next;
headnod->next = newnod;
}
4.删除节点
5.打印链表
写一个printlist函数打印,链表我们打印从第二个所以我们定义一个结构体指针move 指向第二个元素开始打印
先判断move指针指向的地方是不是空指针
如果不是进入循环先打印数据再让指针向后移动
//打印链表
void printlist(struct Node* headnod)
{
//从第二个节点开始打印
struct Node* move = headnod->next;
while (move != NULL)
{
printf("%d ", move->date);
move = move->next;
}
printf("\n");
}
最后在main函数里调用就可以了
int main()
{
struct Node* list = createlist();
insternode(list, 1);
insternode(list, 2);
insternode(list, 3);
printlist(list);
return 0;
}
删除节点这里没有讲,讲的也不是很好,欢迎大家多提提意见