#include<iostream>
using namespace std;
#define MaxSize 50
typedef struct {
char data[MaxSize];
int length;
}SqList;
void InitList(SqList *&L)
{
L = (SqList*)malloc(sizeof(SqList));
L->length = 0;
}
void DestroyList(SqList *L)
{
free(L);
}
int ListEmpty(SqList*L)
{
if (L->length)
{
return true;
}
return false;
}
int ListLength(SqList*L)
{
return (L->length);
}
void DispList(SqList*L)
{
for (int i = 0; i < L->length; i++)
{
cout << L->data[i];
}
cout << endl;
}
bool GetElem(SqList* L, int i, char& e)
{
if (i<1||i>L->length)
{
return false;
}
i--;
e = L->data[i];
return true;
}
int LocateElem(SqList* L, char e)
{
int i = 0;
while (i<L->length&&L->data[i]!=e)
{
i++;
}
if (i>=L->length)
{
return 0;
}
return i + 1;
}
bool ListInsert(SqList*&L,int i,char e)
{
if (i<1||i>L->length+1||L->length>=MaxSize)
{
return false;
}
i--;
for (int j =L->length; j >i; j--)
{
L->data[j] = L->data[j - 1];
}
L->data[i] = e;
L->length++;
return true;
}
bool ListDelete(SqList*&L,int i,char&e)
{
if (i<1||i>L->length)
{
return false;
}
i--;
e = L->data[i];
for (int j = i; j < L->length-1; j++)
{
L->data[j] = L->data[j + 1];
}
L->length--;
return true;
}
int main()
{
SqList* L;
InitList(L);
ListInsert(L, 1, 'a');
ListInsert(L, 2, 'b');
ListInsert(L, 3, 'c');
ListInsert(L, 4, 'd');
ListInsert(L, 5, 'e');
DispList(L);
cout << ListLength(L) << endl;
cout << (ListEmpty(L) ? "非空" : "空") << endl;
char e;
GetElem(L, 3, e);
cout << e << endl;
cout << LocateElem(L, 'a') << endl;
ListInsert(L, 4, 'f');
DispList(L);
ListDelete(L, 3, e);
DispList(L);
DestroyList(L);
return 0;
}
首先作者尝试在void InitList(SqList *&L)等需要+&的部分不加,运行结果说是未初始化本地变量,分析之后发现,我们在主函数中定义了一个指针。
而将一个指针传入是麻烦的,这里用了c++的引用语法,方便了许多,作者搞混了,比如下图例子。定义整型变量a,传入他的地址,用&,形参用int 8b,没有问题,但是第一张图是定义一个指针L。