#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
#include<Status.h>
#include<stdio.h>
#include<stdlib.h>
#define ListSize 250 //可以存储250个数据
#define Increasing 50 //后期每次增加50个数据
typedef int Elemtype;
typedef struct
{
Elemtype *elem;
int length; //目前储存元素的个数
int listsize; //可以储存的元素个数
}SqList;
Status InitList(SqList &L);
Status InsertList(SqList &L,int i,Elemtype e);
//Status Traverse_Print(SqList L);
Status InitList(SqList &L)
{
L.elem=(Elemtype*)malloc(ListSize*sizeof(Elemtype));
if(!L.elem) exit(FALSE);
L.length=0;
L.listsize=ListSize;
return OK;
}
Status InsertList(SqList &L,int i,Elemtype e)
{
if(i<1||i>L.length+1) exit(ERROR) ;
if(L.length>=L.listsize)
{
Elemtype* newbase;
newbase=(Elemtype*)realloc(L.elem,(ListSize+Increasing)*sizeof(Elemtype));
L.elem=newbase;
//因为L.elem重新分配的空间从下一句语句开始,所以不能用L.elem=……
if(!L.elem) exit(OVERFLOW);
L.listsize+=Increasing;
}
int j=L.length-1; //从n开始倒退着像后移动一个地址
for(j;j>=i-1;j--) L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
//不用指针,直接倒退到第i个元素(下标i-1)处,然后将第i个元素更改即可
L.length++;
return OK;
}
void main()
{
SqList L;
InitList(L);
Elemtype a[10]={1,2,3,4,5,6,7,8,9,10};
L.elem=a;
L.length=10;
printf("原顺序表为:\n");
//Traverse_Print(L);
int i;
InsertList(L,3,2);
for(i=0;i<=L.length-1;i++) printf("%d\n",L.elem[i]);
}