该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
头文件:
#pragma once
#ifndef SEQLIST_H
#define SEQLIST_H
const int len = 1000;
template
class SeqList {
public:
SeqList() { length = 0; }//无参构一个造函数,建立空的顺序表
SeqList(DataType a[], int n);//有参构造函数,建立一个长度为n的顺序表
~SeqList() {}//析构函数为空
int Length() { return length; }//求线性表的长度
DataType Get(int i);//按位查找,在线性表中查找第i个元素
int Locate(DataType x);//按值查找,在线性表中查找值为x的元素序号
void Insert(int i, DataType x);//插入,在线性表中第i个位置插入值为x的元素
DataType Delete(int i);//删除操作,删除线性表的第i个元素
void PrintList();//遍历操作,按序号依次输出各元素
private:
DataType data[len];
int length;//线性表的长度
};
#endif
源文件:
#include
using namespace std;
#include"顺序表.h"
template
SeqList::SeqList(DataType a[], int n) {//建立长度为n的顺序表
if (n > len)throw"参数非法";
for (int i = 0; i < n; i++) {
data[i] = a[i];
length = n;
}
}
template
DataType SeqList::Get(int i) {//按位查找
if (i<1 && i>length)throw"查找位置非法";
else return data[i - 1];
}
template
int SeqList::Locate(DataType x) {//按值查找
for (int i = 0; i < length; i++)
if (data[i] == x)return i + 1;
return 0;
}
template
void SeqList::Insert(int i, DataType x) {//插入元素
int j;
if (length >= len)throw"上溢";
if (i<1 || i>length + 1)throw"位置异常";
for ( j = length; j >= i; j--)
data[j] = data[j - 1];
data[j - 1] = x;
length++;
}
template
DataType SeqList::Delete(int i) {//删除操作
if (length == 0)throw"下溢";
if (i<1 || i>length)throw"位置异常";
x = data[i - 1];
for (int j = i; j < length; j++) {
data[j - 1] = data[j];
length--;
return x;
}
template
void SeqList::PrintList() {//遍历操作(依次输出线性表的元素值)
for (i = 0; i < length; i++)
cout << data[i];
}
}
int main() {
int array[] = { 1,2,3,4,5,6,7,8,9,67 };
SeqListArray(array,sizeof(array)/sizeof(*array));
Array.Get(2); //这样写主函数没办法调用顺序表,会报错,求解决办法
Array.Insert(3,66);
Array.Length();
Array.Locate(8);
Array.PrintList();
system("pause");
return 0;
}