您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要介绍了C语言如何编写一个链表,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
本文实例为大家分享了C语言编写一个链表的具体代码,具体内容如下

1.创建头链表
struct Node* Creatlist(){//创建链表头
struct Node *headnode = (struct Node*)malloc(sizeof(struct Node));//创建动态内存链表,指针变量
headnode->next = NULL;//链表初始化
return headnode;
}2.创建节点
struct Node* Creatnode(int num){//创建结点,链表,参数数字域
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));//创建动态内存链表,指针变量
newnode->num = num;
newnode->next = NULL;//链表初始化
return newnode;
}3.插入节点

void Insetlist(struct Node* list, int num){//头插法
struct Node* insetnode = Creatnode(num);
if (list != NULL){
insetnode->next = list->next;
list->next = insetnode;
}
else{
printf("节点不存在\n");
}
}
void Insetlists(struct Node* headnode, int n, int num){//在n节点处插入,参数头节点,在第n个节点处插,插入的数据num
int i = 1;
struct Node *t = headnode;
while (i < n&& t!= NULL){
t = t->next;
i++;
}
if (t != NULL){
struct Node* insetnode = Creatnode(num);
insetnode->next = t->next;
t->next = insetnode;
}
else{
printf("节点不存在\n");
}
}4.修改节点
void Modifynode(struct Node* headnode, int n){//修改节点,参数链表,修改的第n个节点
struct Node* list = headnode;
int i = 0;
while (i < n&&list != NULL){
list = list->next;
i++;
}
if (list != NULL){
printf("请输入你要修改的值\n");
int j = 0;
scanf("%d", &j);
list->num = j;
}
else{
printf("节点不存在\n");
}
}5.删除节点

定义两个指针,一个指向删除节点的上一个节点,一个指向要删除的节点
void Deletnode(struct Node* headnode, int n){//删除第n个节点,
int i = 1;
struct Node *strat = headnode;
struct Node *end = headnode->next;
while (i < n&&end != NULL){
strat = strat->next;
end = end->next;
i++;
}
if (end != NULL){
strat->next = end->next;
free(end);
}
else{
printf("节点不存在\n");
}
}6.打印节点
void Printnode(struct Node* headnode){//打印节点
struct Node* list = headnode;
while ((list->next) != NULL){
list = list->next;
printf("%d\t", list->num);
}
printf("\n");
}7.主函数
int main(){
struct Node* list = Creatlist();
Insetlists(list, 1, 1);
Printnode(list);
int i = 0;
printf("请输入修改哪个节点\n");
scanf("%d", &i);
Modifynode(list, i);
Printnode(list);
printf("请输入删除哪个节点\n");
int n = 0;
scanf("%d", &n);
Deletnode(list, n);
Printnode(list);
system("pause");
return 0;
}感谢你能够认真阅读完这篇文章,希望小编分享的“C语言如何编写一个链表”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。