顺序表不能正常插入元素,本来我是要插入5个元素的,但是这个程序在我输入2个元素后就结束运行了,不知道是什么原因
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 20
#define OVERFLOW -2
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 0
typedef char Status;
typedef struct {
char *elem;
int length;
}SqList;
Status InitLsit(SqList& L) {
L.elem = (char*)malloc(sizeof(char) * MaxSize);
if (!L.elem)
exit(OVERFLOW);
L.length = 0;
return OK;
}
Status ListInsert(SqList& L, int i, char e) {
if (i<1 || i>L.length)
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;
}
Status DeleteList(SqList& L, int i) {
if (i<1 || i>L.length)
return ERROR;
for (int j = i; j < L.length - 1; j++)
{
L.elem[j - 1] = L.elem[j];
L.length--;
}
return OK;
}
void DestroyList(SqList&L) {
if (L.elem)
delete L.elem;
}
void ClearList(SqList& L) {
L.length = 0;
}
int Getlength(SqList L) {
return(L.length);
}
int IsEmpty(SqList L) {
if (L.length == 0)
return 1;
else
return 0;
}
int GetElem(SqList& L, int i, char& e) {
if (i<1 || i>L.length)
return ERROR;
e = L.elem[i - 1];
return OK;
}
int LocateElem(SqList L, char e) {
for (int i = 0; i < L.length; i++)
if (L.elem[i] == e)
return i + 1;
return 0;
}
void PrintList(SqList& L) {
for (int i = 0; i < L.length; i++) {
if (i == L.length - 1)
printf("%c", L.elem[i]);
else
printf("%c ", L.elem[i]);
}
}
int main()
{
int n;
SqList L;
char e;
InitLsit(L);
printf("输入顺序表的元素个数:");
scanf_s("%d", &n);
for (int i = 1; i < n; i++) {
scanf_s("%c", &e);
ListInsert(L, i, e);
}
PrintList(L);
Getlength(L);
}
问题肯定出在ListInsert函数里啊,插入数据的逻辑不正确。
为什么不利用L.length作为下标进行,循环插入数据呢,只要别忘了更新下标值就行,例如L.length++