C语言创建一个线性表,然后输出线性表,如何编写程序?

2024年11月28日 08:37
有1个网友回答
网友(1):

#include
#include
#include

#defineOVERFLOW -2
#define OK 1
#define ERROR 0
#defineLIST_INIT_SIZE 100
#defineLISTINCREMENT 10

typedef intElemType;
typedef intStatus;
//定义顺序存储结构
typedef struct
{
ElemType *elem;
int length;
int listsize;
}SqList;
//初始化顺序表
StatusInitList_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;
}
//自定义创建顺序表
voidCreate_SqList(SqList &L)
{
int c,i=0;
int *newBase;
printf("请输入顺序表元素:\n");
while((scanf("%d",&c))!=EOF)
{
if(i>=L.listsize) //自定义顺序表大小超过初始化大小
{
newBase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
//为初始顺序表以LISTINCREMENT大小重新增加存储空间
if(!newBase)exit(OVERFLOW);
L.elem=newBase;
L.listsize+=LISTINCREMENT;
}
L.elem[i++]=c;
}
L.length=i;
printf("输入的顺序表元素:\n");
for(i=0;i printf("%d ",L.elem[i]);
printf("\n");
}
//在指定位置插入元素
StatusListInsert(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;
*q=e;
++L.length;
return OK;
}
//在指定位置删除元素
StatusListDelete_Sq(SqList &L,int i,ElemType *e)
{
ElemType *p,*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 m,n;
int location,element;
if(!InitList_Sq(L))
{
printf("初始化顺序表失败!\n");
exit(ERROR);
}
Create_SqList(L);
for(m=0;m<3;m++)
{
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("顺序表插入失败!\n");
exit(ERROR);
}
printf("插入顺序表为:\n");
for(int i=0;i<=L.length -1;i++)
{
printf("%d ",L.elem[i]);
}
printf("\n新顺序表一共有%d个元素。\n",L.length);
}
for(n=0;n<3;n++)
{
printf("输入删除位置:");
scanf("%d",&location);
while(location>L.length||location<1)
{
printf("输入位置错误,请重新输入!\n");
scanf("%d",&location);
}
if(!ListDelete_Sq(L,location,&element))
{
printf("删除错误!\n");
exit(ERROR);
}
printf("被删除的元素为:%d \n",element);

printf("被删除后的顺序表为:\n");
for(int j=0;j<=L.length-1;j++)
{
printf("%d ",L.elem[j]);
}
printf("\n新顺序表一共有%d个元素。\n",L.length);
}
}
这个是我最近编写的 顺序表也是线性表的
这里还有链表的程序 用的话再传给你