写一下链式的两种基本的数据插入方法:头插法和尾插法 ,(要写头插法而题目要求是没有头节点的话可以头插法的函数内自己做个头节点),下面是以有头节点为例的代码(代码有重载的函数create_node(),自己想试着运行的话可以构建C++的项目,或者把同名函数改一下就行了)。
更新:把重载的函数修改了,这样建C项目就可以直接运行了。
代码:
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node *ptrNode;
typedef struct node{
datatype data;
ptrNode next;
}lnode;
ptrNode create_node(datatype d)
{
ptrNode ptn = (ptrNode)malloc( sizeof(lnode) );
ptn->next = NULL;
ptn->data = d;
return ptn;
}
ptrNode create_node_null()
{
ptrNode ptn = (ptrNode)malloc( sizeof(lnode) );
ptn->next = NULL;
return ptn;
}
//带头结点 头插
void link_list_front(ptrNode l,datatype d)
{
ptrNode ptn = create_node(d);
ptrNode temp = l->next;
l->next = ptn ;
ptn->next = temp;
}
//尾插
void link_list_rear(ptrNode l,datatype d)
{
ptrNode ptn = create_node(d);
while(l->next)l=l->next;
l->next = ptn;
}
void print(ptrNode l)
{
l=l->next;
while(l)
{
printf("%d ",l->data);
l=l->next;
}
printf("\n");
}
//测试
int main()
{
ptrNode head = create_node_null();
link_list_front(head,3);//当前 3
link_list_rear(head,9);//当前 3 9
link_list_rear(head,4);//当前 3 9 4
link_list_front(head,6);//当前 6 3 9 4
print(head);
return 0;
}
本文介绍了链表数据结构中两种基本的插入方法——头插法和尾插法,提供了带有头节点的C++实现代码。头插法在链表前端插入新节点,而尾插法则在链表末尾添加节点。代码包括创建节点的函数及打印链表的辅助函数,并通过示例展示了如何使用这些方法。
5216

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



