标签:throw private delete 顺序表 线性表 查找 data 打印 row
#include "stdafx.h"
#include <iostream>
using namespace std;
const int MaxSize = 100;
class SeqList{ //定义一个SeqList类
private:
int data[MaxSize]; //存放数据元素的数组
int length; //线性表的长度
public:
SeqList(){length = 0;} //无参构造函数,建立一个空的顺序表
SeqList(int a[],int n); //创建一个长度为n的顺序表;
~SeqList(){} //析构函数为空
int Length(){return length;} //求线性表的长度
int Get(int i); //按位查找,在线性表中查找第i个元素
int locate(int x); //按值查找,在线性表中查找值为x的元素序号
void Insert(int i,int x); //插入操作,在线性表中第i个位置插入值为x的元素
int Delete(int i); //删除操作,删除线性表的第i个元素
void printList(); //遍历操作,按序号依次输出各元素
};
SeqList::SeqList(int a[],int n){
if(n>MaxSize) throw "参数非法";
for(int i = 0;i<n;i++)
data[i] = a[i];
length = n;
}
int SeqList::Get(int i){
if(i < 1 && i > length) throw "查找的范围非法";
else
return data[i-1];
}
int SeqList::locate(int x){
for(int i = 0;i < length;i++)
if(x == data[i])
return i+1;
return 0;
}
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++;
for(int j = 0;j<length;j++){
cout<<data[j]<<" ";
}
}
int SeqList::Delete(int i){
if(length>=MaxSize) 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;
}
void SeqList::printList(){
for (int i = 0; i < length; i++){
cout << data[i] <<" ";
}
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int n;
cin>>n;
int * a = new int[n]; //动态创建数组a;
for(int i = 0;i < n;i++){ //输入元素
cin >> a[i];
}
SeqList example(a,n); //定义一个SeqList 的对象,并初始化
cout<<"数组的长度 ";
cout<<example.Length()<<endl;
cout<<"输入要查找的元素位置 ";
int i;
cin>>i;
cout<<example.Get(i)<<endl;
cout<<"在第j个元素插入数字x输入j,x ";
int j,x;
cin>>j>>x;
example.Insert(j,x);
cout<<endl;
cout<<"查找数值为y的元素下标输入y ";
int y;
cin>>y;
cout<<example.locate(y)<<endl;
cout<<"删除第m个元素输入m ";
int m;
cin>>m;
cout<<example.Delete(m)<<endl;
cout<<"打印SeqList对象 ";
example.printList();
delete a;
return 0;
}
标签:throw private delete 顺序表 线性表 查找 data 打印 row
原文地址:http://www.cnblogs.com/yym-1688/p/yuance.html