以顺序表作存储结构,实现线性表的创建、插入。
顺序表的类型描述
#define MAXSIZE 10 // MAXSIZE为最大数据元素数目
typedef int ElemType;
typedef struct
{ ElemType *elem;
int length;
} SqList;
输入格式:
输入分三行
- 第一行 元素个数
- 第二行 元素的值。元素间以空格分隔。
- 第三行 待插入的位置和元素值
具体格式参看输入样例
输出格式:
输出分两行
- 第一行 插入前的线性表
- 第二行 插入后的线性表。 如因插入位置错误失败,输出
Insert position error!
如因为表满插入失败,输出OVERFLOW!
具体格式参看输出样例
输入样例:
5
1 3 5 7 9
3 4
输出样例:
Before:(1,3,5,7,9)
After:(1,3,4,5,7,9)
输入样例:
5
1 3 5 7 9
7 10
输出样例:
Before:(1,3,5,7,9)
Insert position error!
输入样例:
10
1 2 3 4 5 6 7 8 9 10
6 7
输出样例:
Before:(1,2,3,4,5,6,7,8,9,10)
OVERFLOW!
// #include <iostream>
#include <stdio.h>
#define MAXSIZE 10
typedef int ElemType;
typedef struct{
ElemType *elem;
int length;
}SqList;
//初始化顺序表
int InitSqList(SqList &L){
L.elem=new ElemType[MAXSIZE];
if(!L.elem) return 0;
L.length=0;
return 1;
}
//插入
int InsertList(SqList &L,int i,ElemType e){
if(i<1||i>L.length+1){
printf("Insert position error!");
return 0;
}
if(L.length==MAXSIZE) {
printf("OVERFLOW!");
return 0;
}
int j;
for(j=L.length;j>=i;j--){
L.elem[j]=L.elem[j-1];
}
L.elem[j]=e;
L.length++;
return 1;
}
//遍历
int TraList(SqList L){
if(L.length==0) return 0;
int i;
printf("(");
for(i=0;i<L.length;i++){
printf("%d",L.elem[i]);
if(i!=L.length-1) printf(",");
}
printf(")");
}
main(){
int n,i;
ElemType e;
SqList L;
//创建顺序表
InitSqList(L);
//插入个数
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&e);
InsertList(L,i,e);
}
printf("Before:");
TraList(L);
printf("\n");
scanf("%d %d",&i,&e);
int j=InsertList(L,i,e);
if(j!=0){
printf("After:");
TraList(L);
}
}