打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
单向链表应用函数
注意:创建节点,一定要销毁节点。
#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)
return1;
pn->next= head->next;
head->next= pn;
return0;
}
// 尾插入法
// 0-成功 1-失败
int insert_end(node_t *head,node_t *pn)
{
node_t*tail = NULL;
if(NULL== pn)
return1;
tail= head;
while(tail->next!= NULL)
tail= tail->next;
tail->next= pn;
pn->next= NULL;
return0;
}
// 打印所有节点内容
void print(node_t *head)
{
node_t*cur = NULL;
cur= head->next;
while(cur!= NULL){
printf("%d",cur->data);
cur= cur->next;
}
printf("\n");
}
// 销毁所有节点
void destroy(node_t *head)
{
node_t*del =NULL,*n_node = NULL;
del = head->next;
while(del != NULL){
n_node= del->next;
free(del);
del = n_node;
}
init(head);
}
// 应用函数
// 创建长度为 len 的链表并输入内容
// 返回创建的节点数
int create_link(node_t *head,int len)
{
inti = 0;
node_t*n_node = NULL;
printf("输入 %d 个数:\n",len);
for(i= 0;i < len;i++){
n_node= create(sizeof(node_t));//创建新节点
if(NULL== n_node)
returni;
scanf("%d",&n_node->data); // 输入数据
insert_end(head,n_node);      // 插入链表
}
returni;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
15道使用频率极高的基础算法题
链表反转
查找算法集
Java链表数据结构及其简单使用方法解析
单链表翻转
给出一个单向链表的头指针,输出该链表中倒数第K个节点的指针
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服