【问题描述】线性表L采用顺序存储结构sqlist,实现线性表插入元素操作:
函数原型:status listinsert(sqlist &l,int i,elemtype e)
初始条件:线性表l已经存在,1<=i<=listlength(l)+1。
操作结果:在线性表的第i个位置之前插入元素e,线性表长度加1。
【输入形式】
第1行:整型数据n,表示线性表的长度;
第2行:n个整型数据,表示线性表的n个元素;
第3行:2个整型数据i和e;i表示插入位置,e表示待插入的素数;
【输出形式】
执行正确:
第1行:输出线性表长度;
第2行:输出线性表元素;
执行失败:输出"error";
【样例输入】
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
#define error 0
#define ok 1
typedef int status;
#define listinitsize 100
#define listincrement 10
typedef char elemtype;
typedef struct{
elemtype *elem;
int length;
int listsize;
}sqlist ;
status initlist(sqlist &l)//构造一个空的线性表L
{
l.elem=(elemtype *)malloc(listinitsize*sizeof(elemtype));
if(!l.elem) exit(error);//存储分配失败
l.length=0;
l.listsize=listinitsize;//初始存储容量
return ok;
}
//顺序表实验4个辅助函数:
status inputlist(sqlist &l)//顺序表输入
{ int i,n;
//printf("please input the length of the sqlist:");
scanf("%d",&n);
l.length=n;
//printf("please input the data of the sqlist:");
for (i=0;i<=l.length-1;i++) scanf("%d",&l.elem[i]);
return ok;
}
status listtraverse(sqlist l)//顺序表输出
{ int i;
// printf("the length of the sqlist:");
printf("%d\n",l.length);
//printf("the data of the sqlist:");
for (i=0;i<=l.length-1;i++) printf("%d ",l.elem[i]);
//printf("\n");
return ok;
}
status destroylist(sqlist &l)//顺序表撤销
{ free(l.elem);
l.length=0;
l.listsize=0;
return ok;
}
status clearlist(sqlist &l)//顺序表重置
{
l.length=0;
return ok;
}
/*
int locateelem(sqlist l,elemtype e)
{
int a;
for(int i=0;i<l.length;i++)
{
if(l.elem[i]==e)
{
a=i+1;
//cout<<a<<endl;
return ok;
}
//else cout<<"error"<<endl;
else return error;
}
}*/
status listinsert(sqlist &l,int i,elemtype e)
{
int j;
if(i<1||i>l.length+1)
return error;
else
{
for(j=l.length;j>=i-1;--j)//j=3;j<=2;--j 6 6 6 a 0 1 2 (3
{
l.elem[j]=l.elem[j-1];//3=2; 2=1 1=0
}
l.elem[i-1]=e;
++l.length;
return ok;
// l.elem[j-1]=e;return ok;
}
//l->elem[j]=l->elem[j-1];
}
int main()
{
sqlist l;
initlist(l);
inputlist(l);//输入数据
int i;int e;
scanf("%d%d",&i,&e);
if(listinsert(l,i,e))
{
//cout<<l.length+1<<endl;
cout<< listtraverse(l);
}
else printf("error");
destroylist(l);
return 0;
}