#include
#include<malloc.h>
using namespace std;
#define MaxSize 20
#define elemtype int
typedef struct
{
elemtype date[MaxSize];
int length;
}SqList;
int main() {
int a[MaxSize];
for (int i = 0; i < 9; i++) {
cin >> a[i];
}
SqListL= (SqList)malloc(sizeof(SqList));
void chushi1(SqList*);
chushi1(L);
void chushi2(SqList*, int a[], int);
chushi2(L, a, 15);
bool ListInsert(SqList*, int, int);
bool ListDelete(SqList*, int,int);
ListInsert(L, 6, 26);
int e = 0;
ListDelete(L, 7,e);
void shuchu(SqList*);
shuchu(L);
}
void chushi1(SqList*& L) {
L->length = 0;
}
void chushi2(SqList * &L, int a[], int n) {
int i = 0, k = 0;
while (i < n)
{
L->date[k] = a[i];
k++, i++;
}
L->length = k;
}
bool ListInsert(SqList*& L, int i,int e) {
int j;
if (i<1 || i>L->length + 1 || L->length == MaxSize) {
return false;
i--;
for (j = L->length; j > i; j--)
L->date[j] = L->date[ j- 1];
L->date[i] = e;
L->length++;
return true;
}
}
bool ListDelete(SqList*& L, int i,int&e) {
int j;
if (i<1 || i>L->length)
return false;
i--;
e = L->date[i];
for (j = i; j < L->length - 1; j++)
L->date[j] = L->date[j + 1];
L->length--;
return true;
}
void shuchu(SqList* L) {
for (int i = 0; i < L->length; i++)cout << L->date[i];
cout << endl;
}
哪位大佬帮我看一下/新手/c++线性表的顺序存储结构/没报错但就是运行失败
insert函数中return false 位置不对啊
1.malloc的问题,你的代码中,所有的函数都用了引用,如果用了引用,完全没必要再去malloc了,顺序表声明以后,就已经分配内存了,再去malloc就是多此一举,当然用了malloc也没有问题(下面修改的代码中就没给你删)
2.代码中,main函数中声明函数的时候,没有用引用,下面函数实现的时候反而加上了引用&,编译器会认为他们是不同的函数。
3.ListInsert函数中,判断i是否有效的时候,if的{}位置不对,}应该在return false后面,而不是在最后。
代码修改如下:
#include <iostream>
#include <malloc.h>
using namespace std;
#define MaxSize 20
#define elemtype int
typedef struct
{
elemtype date[MaxSize];
int length;
}SqList;
int main()
{
int a[MaxSize];
for (int i = 0; i < 9; i++)
{
cin >> a[i];
}
SqList* L= (SqList*)malloc(sizeof(SqList));
void chushi1(SqList*&);
chushi1(L);
void chushi2(SqList*&, int a[], int);
chushi2(L, a, 15);
bool ListInsert(SqList*&, int, int);
bool ListDelete(SqList*&, int,int&);
ListInsert(L, 6, 26);
int e = 0;
ListDelete(L, 7,e);
void shuchu(SqList*);
shuchu(L);
return 0;
}
void chushi1(SqList*& L) {
L->length = 0;
}
void chushi2(SqList * &L, int a[], int n) {
int i = 0, k = 0;
while (i < n)
{
L->date[k] = a[i];
k++,i++;
}
L->length = k;
}
bool ListInsert(SqList*& L, int i,int e) {
int j;
if (i<1 || i>L->length || L->length == MaxSize)
{ //修改1 i<1 || i>L->length + 1 || L->length == MaxSize
return false;
}
i--;
for (j = L->length; j > i; j--)
L->date[j] = L->date[ j- 1];
L->date[i] = e;
L->length++;
return true;
//} //结束的括号应该在return false下面
}
bool ListDelete(SqList*& L, int i,int&e) {
int j;
if (i<1 || i>L->length)
return false;
i--;
e = L->date[i];
for (j = i; j < L->length - 1; j++)
L->date[j] = L->date[j + 1];
L->length--;
return true;
}
void shuchu(SqList* L) {
for (int i = 0; i < L->length; i++)cout << L->date[i];
cout << endl;
}
C++最好用new delete代替 malloc free;