#include <iostream>
using namespace std;
#define LIST_INIT_SIZE 100 //初始化分配量
#define LISTINCREMENT 10 //存儲空間的分配增量
typedef int Status;
typedef int ElemType;
typedef struct{
ElemType *elem;//儲存空間基址
int length;//當前長度
int listsize;//當前的分配的存儲容量 (以sizeof (ElemType)為單位)
}SqList;
Status InitList_sq(SqList &L){
L.elem = (ElemType *)malloc(LIST_INIT_SIZE *sizeof(ElemType));
if ( !L.elem)exit(1);//存儲分配失敗
L.length = 0; //空表長度為0
L.listsize =LIST_INIT_SIZE;//初始儲存容量
return true;
}
Status ListInsert_Sq(SqList &L,int i,ElemType e)
{
//在順序線性表L中第i個位置之前插入新的元素e
//i的合法值為1<=i<=ListLength_Sq(L)+1
if(i <1 || i> L.length + 1)
return false; //i值不合法
if(L.length >= L.listsize) //當前存儲空間已滿,增加分配
{
ElemType *newbase = (ElemType *)realloc(L.elem,(L.listsize + LISTINCREMENT )* sizeof(ElemType));
if(!newbase)
exit(1); //存儲分配失敗
L.elem = newbase;//新基址
L.listsize += LISTINCREMENT; //增加存儲容量
}
ElemType *q = &(L.elem[i-1]);//q為插入位置
for(ElemType *p = &(L.elem[L.length-1]);p>=q;--p)
*(p+1) = *p; //插入位置及之後的元素右移
*q = e; //插入e
++L.length; //表長增1
return true;
}
int main()
{
SqList L;
InitList_sq(L);
ListInsert_Sq(L,1,2);
return 0;
}