实验目标:
实验源码:
#include <iostream>
using namespace std;
#define LIST_INIT_SIZE 100
#define INCREMENT 10
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
int listsize;
}SqList;
typedef int Status;
//算法2.3,构造一个空的顺序表
Status 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;
}
//算法2.4
Status 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+10)*sizeof(ElemType));
if(!newbase) exit(OVERFLOW);
L.elem = newbase;
L.listsize +=10;
}
q = &(L.elem[i-1]);
for(p=&(L.elem[L.length-1]);p>=q;--p)
*(p+1)=*p;
*q = e;
++L.length;
return OK;
}
//算法2.5
Status ListDelete_Sq(SqList &L,int i,ElemType &e) {
int *p,*q;
if((i<1) || (i>L.length))
return ERROR;
p = &(L.elem[i-1]);
e = *p;
q = L.elem + L.length-1;
for(++p;p<=q;++p)
*(p-1) = *p;
--L.length;
return OK;
}
void print(SqList L) {
int i;
for(i=1;i<=L.length;i++)
printf("%d ",L.elem[i-1]);
printf("\n");
}
int main()
{
SqList L;
int i,e;
int a[5]={1,2,3,4,5};
i=InitList_Sq(L);
printf("%d\n",i);
for(i=1;i<=5;i++)
ListInsert_Sq(L,i,a[i-1]);
printf("插入后的表为:");
print(L);
ListDelete_Sq(L,1,e);
printf("删除的元素为%d\n",e);
printf("删除后的表为:");
print(L);
return 0;
}