数据结构|线性表 | 数组

头文件

#ifndef _SQLIST_FUNC_H_ #define _SQLIST_FUNC_H_#define MAXSIZE 20 #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0typedef int ElemType; typedef int status; //线性表 typedef struct { ElemType data[MAXSIZE]; intlength; intsize ; }sqlist; //函数声明 status get_element(sqlist l,int i,ElemType *e); status insert_element(sqlist *l,int i,ElemType e); status delete_element(sqlist *l,int i,ElemType *e); #endif

功能函数
  • 获取元素
/*func:Gets the linear table element. para: l:linear table i:Get the i element e:Use e return element return: success:OK fail:ERROR */ status get_element(sqlist l,int i,ElemType *e) { if(l.length == 0 || i < 1 || i > l.length) { return ERROR; }*e = l.data[i-1]; return OK; }

  • 在某个位置插入元素
/*func:Inserts an element into a linear table before i position. para: l:linear table i:Insertion position. e:The element to be inserted. return: success:OK fail:ERROR */ status insert_element(sqlist *l,int i,ElemType e) { intk = 0; if(!l || l->length >= l->size || i > l->size || i < 1) { return ERROR; }for(k = l->length-1; k >= i-1; k--) { l->data[k+1] = l->data[k]; } l->data[i-1] = e; l->length++; return OK; }

  • 删除某个元素
/*func:Delete an element into a linear table. para: l:linear table i:delete position. e:The element to be deleted. return: success:OK fail:ERROR */ status delete_element(sqlist *l,int i,ElemType *e) { intk = 0; if(!l || i < 1 || i > l->length) { return ERROR; }*e = l->data[i-1]; for(k = i-1; k < l->length; k++) { l->data[k] = l->data[k+1]; } l->length--; returnOK; }

    推荐阅读