C语言:【动态顺序表】动态顺序表的在指定位置插入元素Insert,以及指定元素Find
2016-02-19 22:10
507 查看
#include<stdio.h> #include<stdlib.h> #include<assert.h> #include<string.h> #include<malloc.h> typedef int DateType; typedef struct SeqList { DateType *arr; size_t capacility; size_t size; }SeqList; //创建空间 void CheckCapa(SeqList *Seq) { assert(Seq); if (Seq->size >= Seq->capacility) { Seq->capacility = 2 * Seq->capacility + 3; Seq->arr = (DateType*)realloc(Seq->arr, Seq->capacility * sizeof(DateType)); } } //初始化动态顺序表 void initSeqList(SeqList *Seq) { Seq->arr = NULL/* malloc(sizeof(DateType) * 3)*/; Seq->capacility = 0; Seq->size = 0; } //销毁空间 void DestroySeq(SeqList *Seq) { Seq->capacility = 0; Seq->size = 0; free(Seq->arr); Seq->arr = NULL; } //尾插 void PushBack(SeqList *Seq,DateType x) { assert(Seq); CheckCapa(Seq); Seq->arr[Seq->size++] = x; } //插入 void Insert(SeqList *Seq,size_t pos, DateType x) { assert(Seq); assert(pos < Seq->size); CheckCapa(Seq); //思路:插入时将pos+1之后元素往后移腾出一个位置,pos位置放入x。 //鉴于标号从0开始,先移动再加加size。 int index = Seq->size; for (; index >= pos + 1;index--) { Seq->arr[index] = Seq->arr[index - 1]; } Seq->arr[pos] = x; Seq->size++; } //查找 int Find(SeqList *Seq, DateType x) { assert(Seq); int index = 0; for (; index < Seq->size; index++) { if (Seq->arr[index] == x) { return index; } } return -1; } //打印动态顺序表 void PrintSeq(SeqList *Seq) { assert(Seq); int index = 0; if (Seq->size == 0) { printf("当前顺序表为空!\n"); return; } for (index = 0; index < Seq->size; index++) { printf("%d->", Seq->arr[index]); } printf("\n"); } void Test() { SeqList Seq; initSeqList(&Seq); PushBack(&Seq, 1); PushBack(&Seq, 2); PushBack(&Seq, 3); PushBack(&Seq, 4); PrintSeq(&Seq); Insert(&Seq, 2, 10); PrintSeq(&Seq); int ret = Find(&Seq, 20); if (ret == -1) { printf("not exist!\n"); } else { printf("%d\n"); } DestroySeq(&Seq); }
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- 如何写好 C main 函数
- C#数据结构之顺序表(SeqList)实例详解
- Lua和C语言的交互详解
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C语言编程中统计输入的行数以及单词个数的方法
- C语言自动生成enum值和名字映射代码
- 使用C语言判断英文字符大小写的方法
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- C语言中计算正弦的相关函数总结
- 使用C语言详解霍夫曼树数据结构
- 探讨C语言的那些小秘密之断言
- C语言实现BMP转换JPG的方法
- linux----->shell高级编程----1