1.链表节点结构体创建
struct node
{
int data;
struct node *next;
}
2.创建一个头结点并初始化
void init_linklist(struct node *phead)
{
phead->data = 0;
phead->next = NULL;
return;
}
3.在尾部插入数据
bool insert_val_tail(struct node *phead, int val) //尾部插入
{
struct node *pnew = (struct node *)malloc(sizeof(struct node)); //堆区创建一个新节点
if (!pnew) //堆区如果内存已满则创建失败
return false;
pnew->data = val;
pnew->next = NULL;
struct node *pcur; //定义一个临时变量
for (pcur = phead; pcur->next != NULL; pcur = pcur->next) //找到最后一个节点
{
}
pcur->next = pnew; //连接到新节点
return true;
}
4.遍历链表
void print_linklist(struct node *phead)
{
struct node *pcur;
for (pcur = phead->next; pcur != NULL; pcur = pcur->next) //从第一个节点开始遍历
{
printf("%d---->", pcur->data);
}
putchar('\n');
}
5.main函数赋值并打印数据
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main()
{
struct node head; //定义结构体变量
init_linklist(&head); //初始化头节点
insert_val_tail(&head, 10); //尾部插入数据
insert_val_tail(&head, 20);
insert_val_tail(&head, 30);
print_linklist(&head); //打印链表数据
return 0;
}
1万+

被折叠的 条评论
为什么被折叠?



