SeqList.h
#pragma once
#include <iostream>
const int MAXSIZE = 100;
template <class T>
class SeqList
{
public:
// 无参数的构造函数
SeqList();
//有参数的构造函数,使用含有n个元素的数组,并且长度为n
SeqList(const T a[], int n);
~SeqList();
// 按次序遍历顺序表的各个元素
void PrintList();
// 在第i 位置插入x
void Insert(int i, T x);
//删除顺序表中的第i个元素
T Delete(int i);
//获取顺序表上的第i个元素
T Get(int i);
//查找顺序表上值为x的元素
int Locate(T x);
private:
int length;
T data[MAXSIZE];
};
#include <iostream>
template <class T>
SeqList<T>::SeqList(const T a[], int n){
if (n > MAXSIZE)
throw "数组长度超过顺序表最大长度";
for (int i = 0; i < n; i++){
data[i] = a[i];
}
length = n;
}
template <class T>
int SeqList<T>::Locate(T x)
{
for (int i = 0; i < length; i++){
if (x == data[i])
return i + 1;
}
return -1;
}
template <class T>
T SeqList<T>::Get(int i)
{
if (i<0 || i>length)
throw "查找位置非法";
return data[i - 1];
}
template <class T>
T SeqList<T>::Delete(int i)
{
if (0 == length)
throw "下溢异常";
if (i<1 || i>length)
throw "位置异常";
T x = data[i-1];
for (int j = i; j < length; j++){
data[j - 1] = data[j];
}
length--;
return x;
}
template <class T>
void SeqList<T>::Insert(int i, T x)
{
if (length >= MAXSIZE)
throw "上溢异常";
if (i<1 || i>length + 1)
throw "位置异常";
i = i - 1;
for (int j = length; j >= i; j--)
{
data[j] = data[j - 1];
}
data[i] = x;
length++;
}
template <class T>
void SeqList<T>::PrintList()
{
std::cout << "按序号依次遍历线性表中的各个元素" << std::endl;
for (int i = 0; i < length; i++){
std::cout << data[i] << " ";
}
std::cout << std::endl;
}
template <class T>
SeqList<T>::~SeqList()
{
}
template <class T>
SeqList<T>::SeqList()
{
}
main.cpp
#include "SeqList.h"
#include <stdlib.h>
int main(){
int a[7] = { 1, 2, 3, 4, 5, 6, 7 };
SeqList<int> list(a, 7);
list.PrintList();
list.Insert(1, 0);
list.PrintList();
int x = list.Delete(8);
std::cout << "删除的元素:" << x << std::endl;
list.PrintList();
int p = list.Locate(4);
std::cout << "元素4的位置:" << p << std::endl;
system("pause");
return 0;
}
运行结果