顺序表的插入操作

本题要求实现一个函数,在顺序表的第i个位置插入一个新的数据元素e,插入成功后顺序表的长度加1,函数返回值为1;插入失败函数返回值为0;

函数接口定义:

int ListInsert(SqList &L,int i,ElemType e);

其中SqList结构定义如下:

typedef struct

{

 ElemType *elem;

 int length;

}SqList;

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 5
typedef int ElemType;
typedef struct{
    ElemType *elem;
    int length;
 }SqList;
void InitList(SqList &L);/*细节在此不表*/
int ListInsert(SqList &L,int i,ElemType e);
int main()
{
    SqList L;
    InitList(L);
    ElemType e;
    int i;
    scanf("%d%d",&i,&e);
    int result=ListInsert(L,i,e);
    if(result==0){
        printf("Insertion Error.The value of i is unlawful or the storage space is full!");    
    }else if(result==1){
        printf("Insertion Success.The elements of the SequenceList L are:");    
        for(int j=0;j<L.length;j++){
            printf(" %d",L.elem[j]);
        }
    }
    return 0;
}
/* 请在这里填写答案 */

输入格式:

输入数据有1行,首先给出以-1结束的顺序表元素值(不超过100个,-1不属于顺序表元素),然后是插入位置和被插入元素值。所有数据之间用空格分隔。

输入样例:

2 6 4 -1 2 100

输出样例:

Insertion Success.The elements of the SequenceList L are: 2 100 6 4

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

C++ (g++)

输出样例

int ListInsert(SqList &L,int i,ElemType e)
{
    int j=L.length;
    if (i<=0||i>L.length+1||L.length>=MAXSIZE)
    {
        return 0;
    }
    for(;j>=i;j--)
    {
       L.elem[j]=L.elem[j-1];
    }
    L.length++;
    L.elem[i-1]=e;
    return 1;   
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chenshengnannn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值