本题要求实现一个函数,在顺序表S中的第i个位置上插入2个数据(data1, data2)。
函数接口定义:
int insert2(SqList &S, int i, ElemType data1, ElemType data2);
解释接口参数:其中S
, i
,data1
,data2
都是用户传入的参数。 S
是顺序表,有两个成员,一个是elem数组,存放顺序表元素,不特别说明的话元素类型为整型,一个是length(length>=0) ,记录顺序表的长度; i
是指插入的位置。data1
和data2
是指要插入的两个元素。函数返回的值为0或1,0代表插入不成功,1代表插入成功。
裁判测试程序样例:
#include<iostream>
using namespace std;
typedef int Status;
#define MAXSIZE 100 //顺序表可能达到的最大长度
typedef int ElemType;
typedef struct {
ElemType *elem; //存储空间的基地址
int length; //当前长度
} SqList;
Status InitList_Sq(SqList&S) ; // 顺序表的初始化,已实现,不用再定义
void CreatList(SqList &S,int n); //创建含有n个元素的顺序表,已实现,不用再定义
void ViewList(SqList &S) ;//打印顺序表,已实现,不用再定义
int insert2(SqList &S, int i, ElemType data1, ElemType data2);//要实现的函数
int main()
{
SqList S;
ElemType a, b;
int i,n;
InitList_Sq(S);
cin >> n;
CreatList(S,n);
cin >>i>>a>>b;
if (insert2(S, i, a, b) ==0)
{
cout << "插入不成功!";
}
else ViewList(S);
return 0;
}
/* 请在这里填写答案 */
输入样例:
在这里给出一组输入。例如:
10
34 56 12 5 7 55 78 2 90 6
5
10 9
输出样例:
在这里给出相应的输出。例如
34 56 12 5 10 9 7 55 78 2 90 6
代码长度限制 | 16 KB |
时间限制 | 400 ms |
内存限制 | 64 MB |
我写的代码 :
int insert2(SqList &S, int i, ElemType data1, ElemType data2)
{
int j;
if((i<1)||(i>S.length+1))
return 0;
if(S.length==MAXSIZE)
return 0;
if(S.length==MAXSIZE-1)
return 0;
for(j=S.length;j>i-1;j--)
{
S.elem[j+2]=S.elem[j];
}
S.elem[i]=data1;
S.elem[i+1]=data2;
S.length=S.length+2;
return 1;
}
完整的代码 :
#include<iostream>
using namespace std;
typedef int ElemType;
typedef int Status;
#define MAXSIZE 100
typedef struct
{
ElemType *elem;
int length;
}SqList;
Status InitList_sq(SqList &S)
{
S.elem=new ElemType[MAXSIZE];
if(!S.elem) exit(0);
S.length=0;
return 1;
}
void CreatList(SqList &S,int n)
{
int i;
for(i=1;i<=n;i++)
cin >> S.elem[i];
S.length=n;
return;
}
void ViewList(SqList &S)
{
int j;
if(!S.elem) exit(0);
for(j=1;j<=S.length;j++)
cout << S.elem[j] << " ";
return;
}
int insert2(SqList &S, int i, ElemType data1, ElemType data2)
{
int j;
if((i<1)||(i>S.length+1))
return 0;
if(S.length==MAXSIZE)
return 0;
if(S.length==MAXSIZE-1)
return 0;
for(j=S.length;j>i-1;j--)
{
S.elem[j+2]=S.elem[j];
}
S.elem[i]=data1;
S.elem[i+1]=data2;
S.length=S.length+2;
return 1;
}
int main()
{
SqList S;
ElemType a, b;
int i,n;
InitList_sq(S);
cin >> n;
CreatList(S,n);
cin >>i>>a>>b;
if (insert2(S, i, a, b) ==0)
{
cout << "插入不成功!";
}
else ViewList(S);
return 0;
}
小结:
发现错误可以用 “ 打印 ” 的方法观察代码运行
初次运行发现:1、 插入位置不对 ;2、最后的6变成一串数字
经姐姐指导后在for循环中打印S.elem【j+2】,观察代码运行情况。先后更改了for循环的起始位置、结束位置;以及对应的data1、data2位置。
暂时就想到这么多,就这样。