数组的顺序表实现
来源:互联网 发布:零基础java就业班 编辑:程序博客网 时间:2024/05/17 22:07
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define Ok 1;
typedef char ElemType;
#define MAX_ARRAY_DIM 8 //假设数组维数最大为8
typedef struct
{
ElemType *base; //数组元素基地址针
int dim; //数组维数
int *bounds; //数组维界基地址
int *constants; //数组映像函数常量基地址
}Array;
typedef int Status;
Status InitArray(Array &A,int dim,...); //构造一个维数为dim的数组
Status DestroyArray(Array &A); //销毁数组A
Status Value(Array A,ElemType &e,...); //A是n维数组,e为元素变量,随后是n个下标值,若不越界,则e赋值为所指定的A的元素值
Status Assign(Array &A,ElemType e,...); //A是n维数组,e为元素变量,随后是n个下标值,若不越界,则e赋值为所指定的A的元素
Status InitArray(Array &A,int dim,...)
{
int elemtotal=1; //数组元素的个数
va_list ap;
if(dim<1||dim>MAX_ARRAY_DIM) return ERROR;
A.bounds=(int*)malloc(dim*sizeof(int));
if(!A.bounds) exit(-1);
va_start(ap,dim);
for(int i=0;i<dim;++i)
{
A.bounds[i]=va_arg(ap,int);
if(A.bounds[i]<0) return ERROR; //underflow
elemtotal*=A.bounds[i];
}
va_end(ap);
A.base=(ElemType*)malloc(elemtotal*sizeof(ElemType));
if(!A.base) exit(-1);
//求映像函数的常数ci,并存入A.constants[i-1],i=1,...dim
A.constants=(int*)malloc(dim*sizeof(int));
if(!A.constants) return ERROR;
A.constants[dim-1]=1; //A.constants保存的各维的元素数个数,最后一维当然是1了
for(int i=dim-2;i>=0;--i)
A.constants[i]=A.bounds[i+1]*A.constants[i+1];
return Ok;
}
Status DestroyArray(Array &A)
{
if(!A.base) return ERROR;
free(A.base) ;
A.base=NULL;
if(!A.bounds) return ERROR;
free(A.bounds);
A.bounds=NULL;
if(!A.constants) return ERROR;
free(A.constants);
A.constants=NULL;
return Ok;
}
//若AP,指示个小标值合法,则求出该元素在A中相对的地址Off
Status Locate(Array A,va_list ap,int &off)
{
off=0;
for(int i=0;i<A.dim;++i)
{
int ind=va_arg(ap,int);
if(ind<0 || ind>=A.bounds[i]) return ERROR;
off+=A.constants[i]*ind;
}
}
Status Value(Array A,ElemType &e,...)
{
int off;
va_list ap;
va_start(ap,e);
if(int result=Locate(A,ap,off)<=0) return result;
e=*(A.base+off);
return Ok;
}
Status Assign(Array &A,ElemType e,...)
{
int off;
va_list ap;
va_start(ap,e);
if(int result=Locate(A,ap,off)<=0) return result;
*(A.base+off)=e;
return Ok;
}
- 数组的顺序表实现
- 顺序表-数组实现
- 数组实现线性表的顺序存储
- 实现基于静态数组的顺序表
- 静态顺序表的实现(数组实现)
- 实现基于静态数组的顺序表的基本操作
- 基于数组的顺序线性表的实现
- 【顺序表】的定义和实现1数组法
- 利用数组创建的顺序表实现各种功能
- 基于数组实现顺序存储的线性表
- 线性表的顺序存储结构--用数组实现
- 数组的顺序表示与实现
- 数组的顺序结构表示和实现
- 数组的顺序表示与实现
- 数组的顺序表示和实现
- 数组的顺序表示和实现
- 数组的顺序存储和实现
- 【Data】数组的顺序表示与实现
- EXTJS4.x之ToolBar的使用
- hdu1012
- [Hadoop] Hadoop开启调试模式
- iframe导致浏览器内存溢出的解决方法
- HDU 2037 今年暑假不AC (贪心)
- 数组的顺序表实现
- html 5开发工具推荐Aptana Studio 3
- 数据结构_行编辑
- gcc-main-cl_decoded_option
- c++ 判断字符串只包含字母、数字、汉字
- memcached的启动参数和stats命令说明
- 数据结构_符号匹配
- 苏州半日游
- Python下载文件