#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#define OVERFLOW -2
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType;
typedef int Status;
typedef int Status;
typedef struct
{
ElemType *elem;
int length;
int listsize;
}SqList;
{
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->length=0;
L->listsize=LIST_INIT_SIZE;
return OK;
}
{
L->elem=(ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if(!L->elem)exit(ERROR);
L->length=0;
L->listsize=LIST_INIT_SIZE;
return OK;
}
void Create_SqList(SqList *L)
{
int c,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("%3d ",L->elem[i]);
printf("\n");
}
Status ListInsert(SqList *L,int i,ElemType e)
{
ElemType *p,*q,*newbase;
if(i<1 || i>L->length+1)
{
printf("插入位置错误\n");
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;
}
if(i == L->length)L->elem[i+1]=e;
q = &(L->elem[i-1]);
for (p = &(L->elem[L->length-1]);p >= q;--p)
*(p+1)=*p;
*(p+1)=e;/*由csdn网绿色改正,P此时已经指到插入位置前一个位置*/
++L->length;
return OK;
}
{
ElemType *p,*q,*newbase;
if(i<1 || i>L->length+1)
{
printf("插入位置错误\n");
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;
}
if(i == L->length)L->elem[i+1]=e;
q = &(L->elem[i-1]);
for (p = &(L->elem[L->length-1]);p >= q;--p)
*(p+1)=*p;
*(p+1)=e;/*由csdn网绿色改正,P此时已经指到插入位置前一个位置*/
++L->length;
return OK;
}
void main()
{
SqList L;
int location,element;
if(!InitList_Sq(&L))
{
printf("初始化顺序表失败!\n");
exit(ERROR);
}
Create_SqList(&L);
printf("输入插入位置:");
scanf("%d ",&location);
while(location > L.length + 1 || location < 1)
{
printf("输入位置错误,请重新输入!\n");
scanf("%d ",&location);
}
printf("输入插入元素:");
scanf("%d ",&element);
if(!ListInsert(&L,location,element))
{
printf("顺序表插入失败!");
exit(ERROR);
}
printf("插入后的顺序表为:\n");
for(int i = 0;i<=L.length-1;i++)
{
printf("%d ",L.elem[i]);
}
printf("\n新顺序表一共%d个元素。\n",L.length);
}