您的位置:首页 > 其它

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;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: