第三周项目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; }
下面是测试元素存在、所查找的位置存在元素:
下面是测试元素存在、所查找的位置存在元素:
相关文章推荐
- dup和dup2函数 http://www.cnblogs.com/svking/archive/2012/08/10/dup.html
- Objective-C Runtime 运行时之二:成员变量与属性
- PS抠图:将猫咪图片打造成唯美星空效果图
- 从相册中选择图片、自定义View
- 定时器的多种用法
- Bridge桥接模式(设计模式11)
- QT5开发及实例1 计算圆周面积 之新建项目文件
- 单例模式C++实现
- SQL Server 2008 数据库定时自动备份
- Java 模版方法(Template Method)
- [POJ 3468]A Simple Problem with Integers[树状数组区间更新+求和]
- SpringMVC部署步骤
- c++find函数用法
- 结构体变量类型前面的struct能不能省略
- codeforces 574D. Bear and Blocks
- SQL Server ->> 关于究竟ALTER INDEX ... REBUILD会不会导致改变索引选项和Filegroup的验证
- oracle 表空间不足处理
- XSS注入常用语句(整理)
- CSS
- View动画