优点:1.插入 删除 不需移动其他元素, 只需改变指针;2:链表各个节点在内存中空间不要求连续!空间利用率高
缺点:1.访问数组元素效率低;2:数组的存储空间连续,内存空间利用率低
重要!!!欢迎对撸代码有兴趣的同学一起交流,大学生也可!!!带你一起写项目致富!:
视频讲解:https://space.bilibili.com/
1.单链表
struct Node {
int data; //数据域 struct Node* next; //指针域 };

其实通俗来讲链表就像一列火车,每一借车厢里面装载的货物就是各种各样的数据,而连接他们的就是通过指针。
2.如何连接他们呢?
#Include
struct Node {
int data; struct Node* next; } int main() {
struct Node Node1={
1,NULL}; //Node1,其数据域里面存放1,指针域为空 struct Node Node1={
2,NULL}; struct Node Node1={
3,NULL}; //定义好了车厢,接下来要连接车厢 Node1.next=&Node2; //将Node2的地址发送给Node1,完成链接 Node2.next=&Node3; }
此为静态链表(不经常使用)
struct Node*createList() {
//火车头 struct Node*headNode=(struct Node*)malloc(sizeof(struct Node)); //此处malloc作用是向系统申请内存 //初始化变量 headNode->next=NULL; return headNode; } 之后在主函数中调用 struct Node*createList() 函数 接下来创建结点: c struct Node*createList(int data)//创建结点区别在于多了数据域 {
struct Node*newNode=(struct Node*)malloc(sizeof(struct Node));//动态内存申请 newNode->data=data; newNode->next=NULL;//初始化变量 }
结点的插入方法一般有:头插法;尾插法。
我们先来讲链表的打印
链表的打印可以看作,火车到站,装卸工人从你选择的地方拿着记录本,依次往后记录着每节车厢的货物。
void printList(struct Node*headList) {
struct Node* pMove=headNode->next;//pMove就是装卸工人 while(pMove) {
printf("%d",pMove->data);//记录 pMove=pMove->next;//向下一节车厢移动 } printf("\n"); }
插入函数(头插法)
void insertNodeByhead(struct Node* headNode) {
struct Node*newNode=createNode(data);//创建结点 newNode->next=headNode->next; headNode->next=newNode; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/226667.html原文链接:https://javaforall.net
