(1) 设数据元素为整数,实现这样的线性表的顺序存储表示。
(2) 键盘输入10个数据元素,利用顺序表的基本操作,建立该表。
#include <iostream>
using namespace std;
const int maxsize=100;
class SeqList{
public:
SeqList();
SeqList(int a[],int n);
~SeqList();
int Length();
int Get(int i);
int Locate(int x);
void Insert(int i,int x);
int Delete(int i);
int Empty();
void PrintList();
private:
int data[maxsize];
int length;
};
SeqList::SeqList()
{
length=0;
}
SeqList::SeqList(int a[],int n)
{
if(n>maxsize) throw "非法参数";
for(int i=0;i<n;i++)
data[i]=a[i];
length=n;
}
SeqList::Length()
{
return length;
}
SeqList::~SeqList()
{
}
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(data[i]==x) 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++;
}
int SeqList::Delete(int i)
{
int x;
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;
}
int SeqList::Empty()
{
if(length==0)
{
cout<<"此表为空"<<endl;
}
else cout<<"此表不为空"<<endl;
}
void SeqList::PrintList()
{
for(int i=0;i<length;i++)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
int main()
{
int r[10],i,a,b,c;
for(int i=0;i<10;i++)
{
cin>>r[i];
}
SeqList L(r,10);
cout<<"数组:";
L.PrintList();
cout<<"长度:"<<L.Length();
cout<<endl;
cout<<"请输入你想插入的数字和位置:"<<endl;
cout<<"数字:";
cin>>a;
cout<<"位置:";
cin>>b;
L.Insert(b,a);
L.PrintList();
cout<<"请输入你想删除数据的位置:";
cin>>c;
cout<<"你删除的数据是:"<<L.Delete(c)<<endl;
cout<<"删除后的结果是:";
L.PrintList();
return 0;
}