head File:
#ifndef seqlist_H
#define seqlist_H
const int maxsize=100;
class seqlist
{ int data[maxsize]; //Array int length
to store data elements ; //Length of linear list public: seqlist(){length=0;} // No-argument constructor, create an empty sequence table seqlist(int a[],int n); //Constructor with parameters, create a sequence table of length n ~seqlist(){} //destructor int get (int i); //Search by bit, find the i-th element in the linear table int locate(int x); //Search by value, find the element number with the value x in the linear table void insert(int i, int x); //Insert operation, insert an element whose value is x in the i-th position in the linear table int dele(int i); //Delete operation, delete the i-th element of the linear table void printlist(); // Traverse operation, output elements in sequence by serial number };
#endif
Subfunction:
#include<iostream>
using namespace std;
#include"seqlist.h"
seqlist::seqlist(int a[],int n) //Initialization of linear table
{
if(n>maxsize) throw "parameter illegal";
int i ;
cout<<"Please enter the data of the linear table:"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++ )
data[i]=a[i];
length=n;
}
int seqlist::get(int i) //Bitwise search
{
if(i<1&&i>length) throw "Illegal search position";
else return data[ i-1];
}
int seqlist::locate(int x)//Find by value
{
int i;
for(i=0;i<length;i++)
if(data[i]==x)
return i+1 ;
return 0;
}
void seqlist::insert(int i,int x)//插入一个数据元素
{
int j;
if(length>=maxsize) throw"上溢";
if(i<1||i>length+1) throw"位置异常";
for(j=length;j>=i;j--)
data[j]=data[j-1];
data[i-1]=x;
length++;
}
int seqlist::dele(int i)//按位删除一个数据元素
{
int x;
if(length==0) throw"下溢";
if(i>maxsize||i<1) throw"位置错误";
x=data[i-1];
for(;i<length;i++)
data[i-1]=data[i];
length--;
return x;
}
void seqlist::printlist() //遍历操作
{
int i;
for(i=0;i<length;i++)
cout<<data[i]<<"\t";
cout<<endl;
}
Main function:
#include<iostream>
using namespace std;
#include"seqlist.h"
void main()
{
int i;
int *s;
s=new int[maxsize];
cout<<"Please enter the length of the linear table:"<< endl;
cin>>i;
seqlist l(s,i);
cout<<"The original data is:"<<endl;
l.printlist();
l.get(3);
cout<<"The value of the third bit is: "<<l.get(3)<<endl;
l.locate(5);
if(l.locate(5)==0) cout<<"There is no such value in the table"<<endl;
else cout <<l.locate(5)<<"This value is the "<<l.locate(5)<<" bit" in the linear table"<<endl;
try
{
l.insert(4,25);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"The data after the insert operation is:"<<endl;
l.printlist();
try
{l.dele(2);}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"The data after the delete operation is:"<<endl;
l. printlist();
delete []s;
}