# 顺序表的插入与删除

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LIST_INIT_SIZE  100
#define LISTINCREMENT  10
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;

typedef struct
{
ElemType *elem;
int length;
int listsize;
}SqList;
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;
}

int ListLength(SqList L)
{ // 初始条件：顺序线性表L已存在。操作结果：返回L中数据元素个数
return L.length;
}

int GetElem(SqList &L,int i,ElemType &e)
{
if(i>L.length||i<1)
exit(OVERFLOW);
e=L.elem[i-1];
return OK;
}

Status ListInsert_Sq(SqList &L,int i,ElemType e)
{
ElemType *newbase,*p,*q;
if(i>L.length+1||i<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; //插入位置  等价于
q=&(L.elem [i-1]);
for(p=L.elem+L.length-1;p>=q;--p)

*(p+1)=*p;
*q=e;
++L.length;
return OK;
}

Status ListDelect_Sq(SqList &L,int i,ElemType &e)
{
ElemType *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 ListPrint(SqList L)
//线性表输出
{
ElemType *p;
printf("线性表中的元素为：\n");
for(p=L.elem;p<L.elem+L.length;p++)
{
printf("%d",*p);
}
}

void main()
{
SqList L;
int i,j;
ElemType e;
InitList_Sq(L);
printf("input five data \n");
for(i=1;i<=5;i++)
{
scanf("%d",&e);
ListInsert_Sq(L,i,e);
}
ListPrint(L);
printf("输入要删除的位置\n");
scanf("%d",&j);
ListDelect_Sq(L,j,e);
printf("输出被删除的元素");
printf("%d",e);
ListPrint(L);

}