链表通过结构体将数据以一个一个节点的方式存储,然后通过指针将各个节点的地址串联起来。
一、创建结构体
struct list{
//存放数据
int num;
//存放下一节点地址
struct list *next;
};
二、创建表头
// 创建头节点 num为传入数据
struct list *creatList(int num)
{
struct list *head;
head=(struct list *)malloc(sizeof(struct list));
head->num=num;
head->next = NULL; //初始化下一节点位置为空指针
return head; //返回头节点地址
}
三、创建新的节点
//创建新的节点
struct list *creatNode(int num)
{
struct list *newNode;
newNode=(struct list*)malloc(sizeof(struct list));
newNode->num=num;
newNode->next=NULL;//下一节点地址初始化为空
return newNode;//返回新节点地址
}
四、插入方法
void insert(struct list *head,int num)
{
struct list *p=head;
struct list *newNode=creatNode(num);//创建节点
while(p->next!=NULL)//找到尾节点的地址
p=p->next;
newNode->num=num;
newNode->next=NULL;
//将next指向newNode
p->next=newNode;
}
这里可以改进:通过将尾节点的位置存储起来,避免每次插入时循环找尾节点;
同时:可以加入新参数(上一节点地址)实现各种位置的插入;
五、输出链表
void print(struct list *head)
{
struct list *move=head;
do{
printf("%d ",move->num);
move=move->next;//不断更新move的地址遍历链表
}while(move->next!=NULL) ;
printf("%d",move->num);
}
六、主程序
int main()
{
int node_num;
scanf("%d",&node_num);
struct list *head=creatList(node_num);
for(int i=0;i<3;i++)
{
scanf("%d",&node_num);
insert(head,node_num);
}
print(head);
return 0;
}