一、问题描述及代码
main.cpp
/*
烟台大学计算机与控制工程学院
作 者:岳增强
日 期:2018-01-01
问题描述:顺序表的基本运算
*/
#include "list.h"
int main()
{
SqList *sq;
ElemtType x[6]= {5,8,7,2,4,9};
InitList(sq);
CreateList(sq, x, 6);
DisList(sq);
return 0;
}
list.h
#include <stdio.h>
#include <malloc.h>
#include "list.h"
void CreateList(SqList *&L,ElemtType a[],int n)
{
int i=0,k=0;
L=(SqList*)malloc(sizeof(SqList));
while(i<n)
{
L->data[i]=a[i];
k++;
i++;
}
L->length=k;
}
void DestoryList(SqList *&L)
{
free(L);
}
void InitList(SqList *&L)
{
L=(SqList*)malloc(sizeof(SqList));
L->length=0;
}
bool ListEmpty(SqList *&L)
{
return (L->length==0);
}
void DisList(SqList *&L)
{
int i=0;
while(i<L->length)
{
printf("%d ",L->data[i]);
i++;
}
printf("\n");
}
int ListLength(SqList *&L)
{
return (L->length);
}
bool GetElem(SqList *&L,int i,ElemtType& e)
{
if(i<1 || i>L->length)
return false;
e=L->data[i];
return true;
}
int LocateElem(SqList* L,ElemtType e)
{
int i=0;
while(i<L->length && e!=L->data[i])
i++;
if(i>L->length)
return 0;
else
return i+1;
}
bool ListInsert(SqList *&L,int i,ElemtType e)//插入数据元素
{
int j;
if(i<1 || i>L->length)
return false;
i--; //将顺序表逻辑序号转化为物理序号
for(j=L->length;j>i;j--)
L->data[j]=L->data[j-1];
L->data[j]=e;
L->length++;
return true;
}
bool listDelete(SqList *&L,int i,ElemtType e)//删除数据元素
{
if(i<1 || i>L->length)
return false;
i--;
e=L->data[i];
L->length--;
while(i<L->length)
{
L->data[i]=L->data[i+1];
i++;
}
return true;
}
list.h
#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED
#define MaxSize 32
typedef int ElemtType;
typedef struct
{
ElemtType data[MaxSize];
int length;
}SqList;
void CreateList(SqList *&L,ElemtType a[], int n);//用数组创建线性表
void DestoryList(SqList *&L);//销毁线性表
void InitList(SqList *&L);//初始化线性表
bool ListEmpty(SqList *&L);//判断线性表是否为空
int ListLength(SqList *&L);//求线性表的长度
void DisList(SqList *&L);//输出线性表
bool GetElem(SqList *&L,int i,ElemtType &e);//求某个数据元素的值
int LocateElem(SqList *L,ElemtType e);//按元素值查找
bool ListInsert(SqList *&L,int i,ElemtType e);//插入数据元素
bool listDelete(SqList *&L,int i,ElemtType e);//删除数据元素
#endif // LIST_H_INCLUDED
二、运行结果
三、感悟与收获
问题1:在编写CreateList()函数时,我没有为L开辟内存空间。并且在mian()中没有调用InitList()函数就直接使用CreateList()函数,所以在执行到L->data[i]==a[i]这条语句时程序崩溃了。在单步调试中发现了这个问题。如下图所示:
问题2:最初写这个程序时建立的为C文件而非cpp文件,程序运行时出现这个bug:error: expected ';', ',' or ')' before '&' token|
上网一搜发现自己非常菜.....错误的原因是C中没有引用这个用法,C++中才有,所以将程序放在cpp文件中就不会有问题了。