#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 100
#define ERROR 0
#define OK 1
typedef int ElemType;
typedef struct
{
ElemType *elem;
int length;
}SqList;
int InitList(SqList &L)
{
L.elem = new ElemType[MAXSIZE];
if(L.elem==NULL)
return ERROR;
L.length=0;
return OK;
}
int CreateSqList(SqList &L,int n)
{
int i;
for(i=0;i<n;i++)
cin>>L.elem[i];
L.length=n;
return OK;
}
int TraverseSqList(SqList L)
{
for(int i=0;i<L.length;i++)
cout<<L.elem[i]<<" ";
return 0;
}
int InsertList(SqList &L,int i,int e)
{
if((i<1)||(i>L.length+1))
return ERROR;
if(L.length==MAXSIZE)
return ERROR;
for(int j=L.length-1;j>=i-1;j--)
L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
++L.length;
return OK;
}
int main()
{
int n,i,a,b,c;
SqList L;
if(InitList(L)==ERROR)
exit(0);
cout<<"Enter n:";
cin>>n;
CreateSqList(L,n);
cout<<"ÇëÊäÈë²åÈë´ÎÊý:";
cin>>c;
for(int d=1;d<=c;d++)
{
cout<<"ÇëÊäÈë²åÈëλÖÃ:";
cin>>a;
cout<<"ÇëÊäÈë²åÈëÔªËØ:",
cin>>b;
InsertList(L,a,b);
if(InsertList(L,a,b)==ERROR)cout<<"´íÎó"<<endl;
else cout<<"³É¹¦"<<endl;
}
TraverseSqList(L);
}
问题给你找到了,判断插入是否成功那条if语句哪里,你又进行了插入一次,所以才导致插入了两次。
正确做法应该是,定义整形变量保存插入的返回值,然会使用该返回值进行判断插入是否成功!
#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 100
#define ERROR 0
#define OK 1
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
}SqList;
int InitList(SqList &L) {
L.elem = new ElemType[MAXSIZE];
if (L.elem == NULL)
return ERROR;
L.length = 0;
return OK;
}
int CreateSqList(SqList &L, int n) {
int i;
for (i = 0; i < n; i++)
cin >> L.elem[i];
L.length = n;
return OK;
}
int TraverseSqList(SqList L) {
for (int i = 0; i < L.length; i++)
cout << L.elem[i] << " ";
return 0;
}
int InsertList(SqList &L, int i, int e) {
if ((i < 1) || (i > L.length + 1))
return ERROR;
if (L.length == MAXSIZE)
return ERROR;
for (int j = L.length - 1; j >= i - 1; j--)
L.elem[j + 1] = L.elem[j];
L.elem[i - 1] = e;
++L.length;
return OK;
}
int main()
{
int n, i, a, b, c;
SqList L;
if (InitList(L) == ERROR)
exit(0);
cout << "Enter n:";
cin >> n;
CreateSqList(L, n);
cout << "请输入插入次数::";
cin >> c;
for (int d = 1; d <= c; d++) {
cout << "请输入插入位置::";
cin >> a;
cout << "请输入插入元素:",
cin >> b;
int result = InsertList(L, a, b); // 保存返回的结果
// if (InsertList(L, a, b) == ERROR)cout << "´失败" << endl; // 这里又插入了一边
if (result == ERROR)cout << "´失败" << endl;
else cout << "成功" << endl;
}
TraverseSqList(L);
return 0;
}