线性表实验
2015-11-15 23:49
302 查看
//SeqList.h文件
//之前我在写#ifndef时一不小心写成了#ifdef,结果错误发生了一堆一堆的。。。一个“n”造成的错误
//SeqList.cpp文件
//SeqList_main.cpp文件
#ifndef SeqList_H //注意这里#ifndef、#endif的用法 #define SeqList_H const int MaxSize = 10; class SeqList{ public: SeqList(){length = 0;} SeqList(int a[], int n); ~SeqList(){} void Insert(int i, int x); int Delete(int i); int Locate(int x); void PrintList(); private: int data[MaxSize]; int length; }; #endif
//之前我在写#ifndef时一不小心写成了#ifdef,结果错误发生了一堆一堆的。。。一个“n”造成的错误
//SeqList.cpp文件
#include<iostream> using namespace std; #include "SeqList.h" SeqList::SeqList(int a[], int n) { //有参构造函数 if(n > MaxSize) throw "参数非法"; for(int i = 0; i < n; i++) { data[i] = a[i]; length = n; } } void SeqList::Insert(int i , int x) { //插入操作函数 if(length >= MaxSize) throw "上溢"; if(i < 1 || i > length+1) throw "位置非法"; for(int j = length; j >= i; j--) data[j] = data[j-1]; data[i-1] = x; length++; } int SeqList::Delete(int i){ //删除操作函数 if(length == 0) throw "下溢"; if(i<1 || i > length) throw "位置非法"; int x = data[i-1]; for(int j = i; j < length; j++) data[j-1] = data[j]; length--; return x; } int SeqList::Locate(int x) { //查找操作函数 for(int i = 0; i < length; i++) if(data[i]==x) return i+1; return 0; } void SeqList::PrintList() { //打印操作函数 for(int i = 0; i < length; i++) cout << data[i] << " "; cout << endl; }
//SeqList_main.cpp文件
#include<iostream> using namespace std; #include "SeqList.h" void main() { int r[5] = {1,2,3,4,5}; SeqList L(r, 5); cout << "执行插入操作前数据为:" << endl; L.PrintList(); try{ L.Insert(2,3); } catch(char* s) //这个s捕捉的就是“上溢”这个字符串 { cout << s << endl; } cout << "执行插入操作后数据为:"<< endl; L.PrintList(); cout << "值为3的元素位置为:"; cout << L.Locate(3) << endl; cout << "执行删除第一个元素操作,删除前数据为:"<< endl; L.PrintList(); try { L.Delete(1); } catch(char* s) //这个捕捉到的s就是“下溢”或者“位置非法”这两个中的一个 { cout << s << endl; } cout << "删除后数据为: " << endl; L.PrintList(); }
相关文章推荐
- Webkit 网络加载到DOM树创建的堆栈记录
- http-live-streaming 协议分析
- java反射机制
- [MongoDB] Introduce to MongoDB
- Qt 建立连接
- HDOJ-2054(大数比较)(A == B ?)
- chown 使用 ,更改所属主(u),也可以更改所属组(g)
- DOM综合案例、SAX解析、StAX解析、DOM4J解析
- 删除.cpp文件
- Broadcast Reciever的使用
- nginx基础
- ubuntu14.10,解决按照最新版Gnome 15.10后,经典Gnome桌面字体问题!
- ubuntu14.10,解决按照最新版Gnome 15.10后,经典Gnome桌面字体问题!
- ubuntu14.10,解决按照最新版Gnome 15.10后,经典Gnome桌面字体问题!
- Android 实践项目开发二
- js几种继承方式比较
- Week4-1Syntax
- 框架学习总结(一):初识框架
- 亿级Web系统搭建——单机到分布式集群
- 浅析对象访问属性的"."和"[]"方法区别