实际上只是起到数组的作用,但是还是完成了它的类实现
//Sequence_List.h文件
//顺序表类的声明
//基本操作:初始化、查询、插入、删除、打印
#ifndef SEQUENCE_LIST_H
#define SEQUENCE_LIST_H
class Sequence_List
{
private:
int *array; //可以当做顺序表的标识符
int length; //顺序表实际长度
int Max_len; //顺序表规模
public:
Sequence_List(int size); //构造函数,确定顺序表规模
Sequence_List(int size,int t); //重构构造函数
~Sequence_List(){} //析构函数
int search_x(int x); //按值查询
bool Find_k(int k,int *x); //按序号查找
bool insert_k(int k,int x); //在第k个位置插入x
void insert_x(int x); //在顺序表尾插入x
void delete_k(int k); //删除第k个元素
int Squlen(){return length;} //返回当前顺序表长度
void show(); //显示顺序表所有元素
};
#endif
//Sequence_List.cpp文件
//顺序表类的实现文件
#include <iostream>
#include "Sequence_List.h"
using namespace std;
//留出数组第一个元素array[0],从array[1]开始到array[length]
Sequence_List::Sequence_List(int size)
{
Max_len = size+1;
length = 0;
array = new int[size+1];
}
//赋值初始化,对前t个元素进行赋值,t<=size
Sequence_List::Sequence_List(int size,int t)
{
Max_len = size+1;
array = new int[size+1];
for(int i=1;i<=t;i++)
{
cout<<"input the "<<i<<"th data:";
cin>>array[i];
}
length = t;
}
//按值查找x,如果成功返回序号,失败返回0,设置监视哨
int Sequence_List::search_x(int x)
{
array[0]=x;
int i=length;
while(array[i--]!=x) ;
return i+1;
}
//按序号查找第k个元素,查找成功将该元素值传给x,返回true,查找失败返回false
bool Sequence_List::Find_k(int k,int *x)
{
if(k<1||k>length) return false;
*x = array[k];
return true;
}
//在第k个位置插入值为x的元素
bool Sequence_List::insert_k(int k,int x)
{
if(k<1||k>length||length==Max_len) return false;
int i;
for(i=length;i>=k;i--)
array[i+1]=array[i];
array[i]=x;
return true;
}
//直接在顺序表最后插入一个元素
void Sequence_List::insert_x(int x)
{
if(length==Max_len) {cout<<"error"<<endl;return ;}
array[++length]=x;
}
//删除第k个元素
void Sequence_List::delete_k(int k)
{
if(k<1||k>length) { cout<<"error"<<endl;return ;}
for(int i=k;i<length;i++)
array[i]=array[i+1];
length--;
}
//打印全表
void Sequence_List::show()
{
for(int i=1;i<=length;i++)
cout<<array[i]<<' ';
}
还是写了一个小测试主程序,同文件夹下包含了Sequence_List.cpp文件就可以使用这个数据结构了,虽然只是练手之用。
//test.cpp
#include <iostream>
#include "Sequence_List.cpp"
using namespace std;
int main()
{
//构造函数
Sequence_List *L = new Sequence_List(10,5);
//按序号查找
int t;
if(L->Find_k(2,&t)) cout<<"the 2th data is:"<<t<<endl;
//顺序表尾插入x&&按值查找
L->insert_x(25);
cout<<"25 is the "<<L->search_x(25)<<"th"<<endl;
//删除第k个元素&&打印全表
L->delete_k(3);
L->show();
}
文本测试结果:
input the 1th data:1
input the 2th data:2
input the 3th data:3
input the 4th data:4
input the 5th data:5
the 2th data is:2
25 is the 6th
1 2 4 5 25