顺序表插入操作的实现

建立长度为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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值