实验2(答案)

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验二

建立一个顺序表结构来存放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

cout<

}//线性表的显示

void main()

{

ElemType e=’a’;

int i;

SqList L;

InitList_Sq( L);

cout<<"输入几个元素组成线性表"<

//printf(“输入几个元素组成线性表”);

for(i=1;i<=26;i++)

{

ListInsert_Sq( L,i, e++);

}

print(L);

cout<

相关文档
最新文档