您的位置:首页 > 其它

线性表实验

2015-11-15 23:49 302 查看
//SeqList.h文件

#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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: