顺序表指定位置插⼊元素
问题描述:
本题要求实现⼀个函数,在顺序表的第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);/*细节在此不表*/c语言listinsert函数
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;
}
/* 请在这⾥填写答案 */
问题分析:
遍历顺序表后移元素,注意点:数组长度的判断
输⼊:
2 6 4 -1 2 100
int ListInsert(SqList &L,int i,ElemType e){
if(i<1||i>L.length+1||L.length>=MAXSIZE)
return0;
for(int k=L.length; k>=i; k--)
L.elem[k]=L.elem[k-1];
L.elem[i-1]=e;
L.length++;
return1;
}
输出:
Insertion Success.The elements of the SequenceList L are: 2 100 6 4

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。