建立一个顺序表结构来存放26个英文字母组成的线性表(a,b,c,…,z),请写出C语言程序。并在此基础上,设计在顺序表的任意一个位置插入新的字母。
实现思路:先开辟头指针,然后陆续为每个数据元素开辟存储空间并赋值,并及时将地址送给前面的指针。
插入函数:参见课本
#include #include #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #define ElemType char #define OVERFLOW -2 #define OK 1 #define ERROR 0 #define N 6 typedef struct{ ElemType *elem; int length; int listsize; }SqList; int InitList_Sq(SqList & L){ L.elem=(ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType)); if(! L.elem) exit(OVERFLOW); L.length=0; L.listsize=LIST_INIT_SIZE; return OK; }//线性表的初始化 int ListInsert_Sq(SqList & L,int i,ElemType e){ int *newbase, *p, *q; if(i<1 || i>L.length+1) return ERROR; if(L.length >= L.listsize){ newbase=(ElemType *) realloc (L.elem,(L.listsize+LISTINCREMENT) * sizeof (ElemType)); if(!newbase) exit (OVERFLOW); L.elem=newbase; L.listsize +=LISTINCREMENT; } q=&(L.elem[i-1]); for (p=&(L.elem[L.length -1]);p>=q;p--) *(p+1)=*p; *q=e; ++L.length ; return OK; }//线性表的插入 void print (SqList L){ for(int i=0;i void main() { ElemType e=’a’; int i; SqList L; InitList_Sq( L); cout<<"输入几个元素组成线性表"< for(i=1;i<=26;i++) { ListInsert_Sq( L,i, e++); } print(L); cout<