c 语言中的链表
2016-07-19 00:17
357 查看
0: 链表的好处是添加和删除方便,只知道上面和下面的是谁,有点想电影里面的卧底,只有上级和下级,单线联系
1:数组和链表的区别和联系
数组和链表都是可以存储集合数据,但是实现方式和效率不同
a:数组可以快速的实现随机访问查找,对于添加和删除效率较低
a:数组可以快速的实现添加和删除,对于随机查找效率较低
c: 链表比数组更灵活,可以随意的扩大或缩小其存储范围
2: 链表就有点像自行车的链条,一个环节一个环节来连接的
我们是通过指针指向当前的节点的上一个节点和下一个节点
#include <stdio.h> #include <string.h> #include <stdlib.h> //1:节点的结构 struct node{ int value;//数据值 struct node *next; //指针域,指向我的下面一个是谁 };//注意定义struct 后面是要添加;的符号的 //2:在链表前面添加 struct node * add(struct node *list,int n){ struct node *new_node; new_node = malloc(sizeof(struct node));//分配内存,注意使用malloc 一定要将#include <stdlib.h>的头文件写出来 new_node->value = n; new_node->next = list; return new_node; } //3:遍历 void loop(struct node *list){ struct node *p; for(p=list;p!=NULL;p=p->next){//注意这里的NULL 要大写 //printf("%d\n",*p); printf("%d\n",p->value); } printf("如果上面没有输出,就是没有找到"); } //4. search void search(struct node *list,int v){ struct node *p; for(p=list;p!=NULL;p=p->next){//注意这里的NULL 要大写 //printf("%d\n",*p); if(v==p->value){ printf("找到了,值为%d\n",p->value); break; } } } //5.delete,删除要知道前面的界面 struct node * delete(struct node *list,int n){ struct node *cur,*prev; for(cur=list,prev=NULL;cur->next!=NULL&&cur->value!=n;prev=cur,cur=cur->next);//注意这里不用去执行其他的内容 if(cur==NULL){ return list;//直到最后也没有找到 } if(prev==NULL){ list =list->next; }else{ prev->next =cur->next; } free(cur); return list; } int main(void){ struct node *list; list = add(list,10); list = add(list,20); list = add(list,30); //loop(list);//输出的时候是30,20,10 search(list,20); delete(list,20); search(list,20); return 0; }
相关文章推荐
- mysql常用函数整理
- Scala学习(一)
- 机器学习与深度学习资料收纳
- android CoordinatorLayout使用
- linux 命令(1)mkdir
- 数据存储 ----归档解档
- 1025. PAT Ranking (25) PAT 甲级
- linux--03
- HDU 1263 水果
- 自增锁预分配ID
- ubuntu和windows双系统,启动时优先进入windows系统
- LeetCode - 374. Guess Number Higher or Lower
- MyBatis使用DEMO及cache的使用心得
- java---验证码图片的生成
- Idea的使用
- 0142 nginx搭建rtmp协议流媒体服务器总结
- android 开发之画布初步探索
- flask博客中关于文章和图片位置的定义
- 从零开始学_JavaScript_系列(26)——只需要前端知识的ajax教程
- 线程的生命周期,线程结束