线性表的数组实现方式

#include #include typedef int Position; //表示位置的数据类型 typedef int ElementType; //表示顺序表的数据类型 typedef struct LNode LNode,*List; #define MAXSIZE 100 struct LNode{ ElementType data[MAXSIZE]; Position last; //相当于一个尾指针 }; //生成一个顺序表 List makeEmpty() { List ptrL; ptrL=(List)malloc(sizeof(LNode)); //为指向结构菩提的指针分配存储空间 ptrL->last=-1; //last为指针 return ptrL; }//查找 #define ERROR -1 Position Find(List l,ElementType x) { Position i; for(i=0; i<=l->last; ++i) { if(l->data[i]==x) break; } if(i>l->last) return ERROR; else return i; } //在p之前插入一个新的元素 bool insert(List l,ElementType x,Position p) { //判断是否能插入 if(p>l->last+1) { printf("位置不合法/n"); return false; } if(l->last==MAXSIZE-1) { printf("表已满"); return false; } for(Position i=l->last; i>=p; --i) l->data[i+1]=l->data[i]; l->data[p]=x; ++l->last; return true; } bool Delete( List L, Position P ) { /* 从L中删除指定位置P的元素 */ Position i; if( P<0 || P>L->last ) { /* 检查空表及删除位置的合法性 */ printf("位置%d不存在元素", P ); return false; } for( i=P+1; i<=L->last; i++ ) L->data[i-1] = L->data[i]; /* 将位置P+1及以后的元素顺序向前移动 */ L->last--; /* Last仍指向最后元素 */ return true; } int main() { List list1=makeEmpty(); //这个指针指向了一个结构体 return 0; }


    推荐阅读