#include <stdlib.h>
#include <stdio.h>
#define OVERFLOW -2
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType;
typedef int Status;
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(ERROR);
}
L->listsize=LIST_INIT_SIZE;
return OK;
}
void Create_SqList(SqList *L)
{
int c;
int i=0;
int *newBase;
printf("请输入顺序表元素,按ctrl+z结束:\n");
while ((scanf("%d",&c)) != EOF)
{
if (i >= L->listsize)
{
newBase = (ElemType *)realloc
(L->elem,(L->listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newBase)
exit(OVERFLOW);
L->elem=newBase;
L->listsize += LISTINCREMENT;
}
L->elem[i++]=c;
}
L->length = i;
printf("请输入的顺序表元素是:\n");
for (i=0; i<L->length; i++)
printf("%5d",L->elem[i]);
printf("\n");
}
Status ListDelete(SqList *L, int i, ElemType *e)
{
ElemType *p;
ElemType *q;
if (i<1 || i>L->length+1)
{
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 main()
{
SqList L;
int location;
int element;
if (!InitList_Sq(&L))
{
printf("顺序表初始化失败!\n");
exit (ERROR);
}
Create_SqList(&L);
printf("输入删除位置:\n");
scanf("%d",&location);
while(location>L.length || location<1)
{
printf("输入位置错误,请重新输入!\n");
scanf("%d",&location);
}
if(!ListDelete(&L, location, &element))
{
printf("删除错误!\n");
exit (ERROR);
}
printf("被删除的元素为:%d\n",element);
printf("删除后的顺序表为:\n");
for (int i=0; i<L.length; i++)
{
printf("%5d",L.elem[i]);
}
printf("\n新顺序表一共%d 个元素。\n",L.length);
}