注意:创建节点,一定要销毁节点。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
intdata;
structnode *next;
} node_t;
// 创建节点函数
void *create(int size);
// 初始化链表
int init(node_t *head);
// 头插入法
int insert_head(node_t *head,node_t *pn);
// 尾插入法
int insert_end(node_t *head,node_t *pn);
// 打印所有节点内容
void print(node_t *head);
// 销毁所有节点
void destroy(node_t *head);
// 应用函数
// 创建长度为 len 的链表并输入内容
int create_link(node_t *head,int len);
int main()
{
node_t*head = NULL;
intlen = 0;
if(init(head= create(sizeof(node_t))) != 0){
printf("初始化链表失败\n");
exit(0);
}
printf("长度:");
scanf("%d",&len);
create_link(head,len);
print(head);
destroy(head);
free(head);
head= NULL;
return0;
}
// 创建节点函数
// 成功返回新节点首地址,失败返回 NULL
void *create(int size)
{
returncalloc(1,size);
}
// 初始化链表
// 0-成功 1-失败
int init(node_t *head)
{
if(NULL== head)
return1;
head->next= NULL;
return0;
}
// 头插入法
// 0-成功 1-失败
int insert_head(node_t *head,node_t *pn)
{
if(NULL== pn)