您的位置:首页 > 其它

第三周项目1 顺序表的基本运算(增加四个函数)

2015-09-16 19:34 716 查看

代码如下:

/*
*          烟台大学计算机与控制工程学院
*文件名称:main.cpp
*作    者:王旭
*完成日期:2015年9月16日
*版 本 号:v1.0
*
*问题描述:测试“建立线性表”的算法CreateList,
实现“输出线性表”的算法DispList。
实现判断线性表是否为空的算法ListEmpty
增加求线性表的长度ListLength的函数并测试;
          增加求线性表L中指定位置的某个数据元素GetElem的函数并测试;
          增加查找元素LocateElem的函数并测试;

*
*输入描述:输入你要查找的元素和你要查找的位置
*程序输出:给出所查找的数据元素的位置,以及给出的位置的元素
*/
#include <iostream>
using namespace std;
#include <malloc.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
} SqList;

void CreateList(SqList *&L, ElemType a[], int n);     //创建线性表
void DispList(SqList *L);                             //输出线性表DispList(L)
bool ListEmpty(SqList *L);                            //判定是否为空表ListEmpty(L)
int ListLength(SqList *L);                            //求线性表的长度ListLength(L)
bool GetElem(SqList *L,int i,ElemType &e);            //求某个数据元素值GetElem(L,i,e)
int LocateElem(SqList *L, ElemType e);                //按元素值查找LocateElem(L,e)

int main()
{
SqList *sq;
ElemType x[6]= {5,8,7,2,4,6};
ElemType a;
int s1,s2;
int loc;
CreateList(sq, x, 6);
DispList(sq);

printf("表长度:%d\n", ListLength(sq));           //测试求长度

cout<<"请输入你要查找的元素的位置:";             //测试查找元素的位置
cin>>s2;

if(GetElem(sq, s2, a))
cout<<"位置为"<<s2<<"的元素为:"<<a<<endl;
else
cout<<"位置为"<<s2<<"的元素不存在"<<endl;

cout<<"请输入你要查找的元素:";                   //测试查找元素
cin>>s1;

if((loc=LocateElem(sq, s1))>0)
cout<<"值为"<<s1<<"的元素是第"<<loc<<"个元素"<<endl;
else
cout<<"没有值为"<<s1<<"的元素";
return 0;
}

void CreateList(SqList *&L, ElemType a[], int n)      //用数组创建线性表
{
int i;
L=(SqList *)malloc(sizeof(SqList));               //分配存放线性表得空间
for (i=0; i<n; i++)                               //放置数据元素
L->data[i]=a[i];
L->length=n;                                      //设置长度
}
void DispList(SqList *L)                              //输出线性表DispList(L)
{
int i;
if (ListEmpty(L))
return;
for (i=0; i<L->length; i++)
printf("%d ",L->data[i]);
printf("\n");
}
bool ListEmpty(SqList *L)                             //判定是否为空表ListEmpty(L)
{
return(L->length==0);
}

int ListLength(SqList *L)                             //求线性表的长度ListLength(L)
{
return(L->length);
}

bool GetElem(SqList *L,int i,ElemType &e)             //求某个数据元素值GetElem(L,i,e)
{
if (i<1 || i>L->length)
return false;
e=L->data[i-1];
return true;
}

int LocateElem(SqList *L, ElemType e)                 //按元素值查找LocateElem(L,e)
{
int i=0;
while (i<L->length && L->data[i]!=e) i++;
if (i>=L->length)
return 0;
else
return i+1;
}



下面是测试元素存在、所查找的位置存在元素:




下面是测试元素存在、所查找的位置存在元素:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: