版权声明:请勿商业化使用 https://blog.csdn.net/qq_40991687/article/details/89545505
问题描述:
本题要求实现一个函数,要求将顺序表的第i个元素删掉,成功删除返回1,否则返回0; 函数接口定义:int ListDelete(SqList &L,int i);
其中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 ListDelete(SqList &L,int i);
int main()
{
SqList L;
InitList(L);
int i;
scanf("%d",&i);
int result=ListDelete(L,i);
if(result==0){
printf("Delete Error.The value of i is illegal!");
}else if(result==1){
printf("Delete 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 1
int ListDelete(SqList &L,int i) {
if(i<1||i>L.length)
return 0;
else {
for(int k=i; k<L.length+1; k++)
L.elem[k-1]=L.elem[k];
L.length--;
return 1;
}
}
输出:
Delete Success.The elements of the SequenceList L are: 6 4