c语言数据结构分析2之 链表插入删除
2011-08-14 18:22
405 查看
#include <stdlib.h> #include <stdio.h> struct test{ int value; struct test *next; }; struct test* create(){ //创建create 函数,返回 struct test* 结构指针 返回的是头部指针 test *head,*tail,*p; head=tail=NULL; //head 是保存头部指针,p是当前指针,tail是临时替换的指针,是用来过度的 int i; for(int j=0;j<4;j++) { scanf("%d",&i); //(数据类型)malloc(sizeof(数据类型)) 动态分配内存,一定要记得用free() 消毁 p=(struct test*)malloc(sizeof(struct test)); //创建结构并开屁空间 p->value=i; p->next=NULL; if(head==NULL) { head=tail=p; //保存头部指针 } else{ tail=tail->next; //第二次set tail->next 有值了 相当于移动两个变量 的指针 } tail->next=p; //当前指针追加在未尾; } return head; }; struct test* insert(struct test* ar,int a,int b) //添加记录函数 { // a 是查找的元素,b是要插入的元素 ar 是处理的结构 struct test *p,*q,*s; s=(struct test*)malloc(sizeof(struct test)); s->value=b; if(ar==NULL) //空表时直接返回 { ar=s; s->next=NULL; } if(ar->value==a)//查找替换的元素是头部的话,直接替换指针 { s->next=ar; ar=s; }else{ //否则遍历查找 p=ar; while(p->value!=a && p->next!=NULL) //当找到 a 值的话,while就结束了 { q=p; //保存 最后一次循环的p p=p->next; } if(p->value==a) //循环后的指针 { q->next=s; //p 已经是保存下一次p的指针了 所以p 的上一次指针是 q s->next=p; }else //否则就追加在后面 { p->next=s; s->next=NULL; } } return ar; } struct test* del(struct test* ar,int n) //删除记录函数 { struct test *q,*p; if(ar==NULL) printf("the table is null\n"); else if(ar->value==n) { ar=ar->next; }else { p=ar; while(p->next!=NULL && p->value!=n) { q=p; p=p->next; } if(p->value!=n) printf("no the num\n"); else { q->next=p->next; free(p); } } return ar; } void showDate(struct test* p) //显示记录函数 { while (p) { printf("%d\n",p->value); p=p->next; } } int main(int argc, char* argv[]) { struct test *p,*head; int a,b,d; head=NULL; p=create(); head=p; showDate(p); printf("num\n"); //插入操作 scanf("%d",&a); printf("insert num\n"); scanf("%d",&b); p=insert(head,a,b); head=p;//再次保存修改后的数据 printf("new p\n"); showDate(p); printf("del num\n"); //删除操作 scanf("%d",&d); p=del(head,d); showDate(p); return 0; }
相关文章推荐
- 【数据结构】C语言实现链表节点的插入和删除
- 【数据结构】C语言实现链表节点的插入和删除
- 数据结构双向循环链表的C语言实现(插入,查询,删除)
- 关于动态存储分配函数的调用,在已经过排序的数组中查找及删除内容的操作,余数的分析,删除字符数组中的空格,对链表的逆置,在源字符串中查找子字符串的个数,函数指针以及函数的调用,循环赋值带来的问题以及插入
- 数据结构:链表插入和删除算法的演示
- 数据结构Java实现03----单向链表的插入和删除
- 数据结构—链表元素的删除和插入
- 数据结构之单向链表操作1-(插入,删除,交换,反转,排序等操作)
- 很简单的数据结构:链表线性存储的创建、取数据、数据添加、数据插入、数据删除
- C语言及程序设计进阶例程-18 链表中结点的插入和删除
- 数据结构---单链表(建立,节点删除,节点插入)
- C语言单向链表的创建、释放、插入、删除、翻转操作练习
- c语言链表基本操作(带有创建链表 删除 打印 插入)
- 链表操作 (C语言)插入,合并,销毁,删除,冒泡排序
- 平衡二叉树的C语言实现(创建、插入、查找、删除、旋转)【数据结构】
- 《C语言及程序设计》教学视频 <18 链表中结点的插入和删除> 示例代码
- 学习笔记——C语言实现单链表的基本操作:创建、输出、插入结点、删除结点、逆序链表
- c语言实现单链表建立,插入,删除,查找,循环链表,静态链表
- 数据结构 单链表创建 插入 删除
- 数据结构C语言>3基本链表>3-5链表的结点删除