顺序表(C语言)
2015-08-06 10:17
435 查看
#include <stdio.h> #include <stdlib.h> #define maxsize 3 #define addsize 2 typedef int elemType; typedef struct { elemType *List;//首地址 int length;//长度 int listSize;//分配的内存大小 } sqList; //初始化顺序链表 void initList(sqList *L) { L->List=(elemType *)malloc(maxsize*sizeof(elemType)); if(!L->List) exit(1); L->length=0; L->listSize=maxsize; } //空间不够重新分配内存 void reaList(sqList *L) { L->List=(elemType *)realloc(L->List,(L->listSize+addsize)*sizeof(elemType)); if(!L->List) exit(1); L->listSize=L->listSize+addsize; } //添加元素 void appendList(sqList *L,elemType elem) { if(L->length==L->listSize) reaList(L); L->List[L->length]=elem; L->length++; } //插入元素 void insertList(sqList *L,elemType elem,int pos) { if(L->length==L->listSize) reaList(L); int i; for(i=L->length;i>pos-1;i--) L->List[i]=L->List[i-1]; L->List[i]=elem; L->length++; } //移除元素 elemType moveList(sqList *L,int pos) { if(pos<0||pos>L->length) exit(1); elemType temp=L->List[pos-1]; int i; for(i=pos-1;i<L->length-1;i++) L->List[i]=L->List[i+1]; L->length--; return temp; } //遍历顺序表 void displayList(sqList *L) { int i; for(i=0;i<L->length;i++) printf("%d\t",L->List[i]); printf("\r\n"); } //返回顺序表元素个数 int lengthList(sqList *L) { return L->length; } //判断顺序表是否为空 bool isEmptyList(sqList *L) { return L->length==0; } //查找元素 int searchList(sqList *L,elemType elem) { int i; if(!isEmptyList(L)) for(i=0;i<L->length;i++) if(L->List[i]==elem) return i+1; printf("找不到该元素\r\n"); return -1; } int main() { sqList L; initList(&L); appendList(&L,1); appendList(&L,2); insertList(&L,6,2); appendList(&L,3); //displayList(&L); appendList(&L,1); insertList(&L,6,4); displayList(&L); elemType temp=moveList(&L,4); printf("移除:%d\t\t",temp); displayList(&L); temp=searchList(&L,3); if(temp!=-1) printf("查找的元素位置为:%d\r\n",temp); temp=searchList(&L,4); if(temp!=-1) printf("查找的元素位置为:%d\r\n",temp); return 0; }
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua和C语言的交互详解
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- C#数据结构揭秘一
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 关于C语言中参数的传值问题
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言内存对齐实例详解
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总