建立长度为n的顺序表,在指定的数据元素item之前插入数据元素data。如果指定的数据元素item不存在,则将data插入到顺序表的尾端。(数据类型为整型)
输入
第一行为顺序表的长度n; 第二行为顺序表中的数据元素; 第三行为指定的数据元素item; 第四行为要插入的数据元素data;
输出
输出结果为顺序表中的数据元素。
样例输入
10
10 20 30 40 50 60 70 80 90 100
50
55
样例输出
10 20 30 40 55 50 60 70 80 90 100
#include <iostream>
using namespace std;
#define Max 100
typedef struct
{
int *elem;
int length;
}SqList;
int InitList(SqList &L)
{
L.elem = new int[Max];
if(!L.elem)
{
return 0;
}
else
{
L.length = 0;
return 1;
}
}
void CreatList(SqList &L)
{
int n;
cin>>n;
int e =0;
for(int i =0;i<n;i++)
{
cin>>e;
L.elem[i]=e;
}
L.length = n;
}
void Insert(SqList &L, SqList &L1,int e ,int m)//插入数据
{
int k = 0,cout =0;
L1.length = L.length+1;
for(int i =0;i<=L.length;i++)
{
if(e==L.elem[i])
{
L1.elem[k++] = m;
L1.elem[k++] = L.elem[i];
}
else
{
L1.elem[k++] = L.elem[i];
cout++;
}
}
if(cout==L.length+1)
{
L1.elem[L.length] = m;
}
}
void TravlList(SqList &L)
{
for(int i=0;i<L.length;i++)
{
cout<<L.elem[i];
if(i!=L.length-1)
{
cout<<" ";
}
}
cout<<endl;
}
int main(int argc, const char * argv[]) {
int e,m;
SqList L,L1;
InitList(L);
InitList(L1);
CreatList(L);
cin>>e>>m;
Insert(L, L1, e, m);
TravlList(L1);
return 0;
}