[c++]代码库
#include <iostream>
#include<stdlib.h>
#include<iomanip>
using namespace std;
typedef int ElemType;
class SeqList
{
private:
ElemType *list;
int maxsize;
int length;
public:
SeqList(int max=0);
~SeqList(void);
bool ListEmpty(void);
int ListLength(void);
void ListTraverse(void);
int LocateElem(int i,ElemType e);
void ListInsert(ElemType &item,int i);
ElemType ListDelete(int i);
ElemType GetElem(int i);
};
SeqList::SeqList(int max)
{
maxsize=max;
length=0;
list=new ElemType[maxsize];
}
SeqList::~SeqList(void)
{
delete []list;
}
bool SeqList::ListEmpty(void)
{
if(length==0)
return true;
else
return false ;
}
int SeqList::ListLength(void)
{
return length;
}
void SeqList::ListTraverse(void)
{
if(!ListEmpty())
for(int i=0;i<length ;i++)
cout<<setw(4)<<list[i];
cout<<endl;
}
void SeqList::ListInsert(ElemType &item,int i)
{
if(length==maxsize)
{
cout<<"顺序表已满"<<endl;
exit(0);
}
if(i<0||i>length)
{
cout<<"参数i出错"<<endl;
exit(0);
}
for(int j=length;j>i;j--)
list[j]=list[j-1];
list[i]=item;
length++;
}
ElemType SeqList::ListDelete(int i)
{
if(length==0)
{
cout<<"顺序表已空"<<endl;
exit(0);
}
if(i<0||i>length-1)
{
cout<<"参数i出错"<<endl;
exit(0);
}
ElemType x=list[i];
for(int j=i;j<length-1;j++)
list[j]=list[j+1];
length--;
return x;
}
ElemType SeqList::GetElem(int i)
{
if(i<0||i>length-1)
{
cout<<"参数i出错"<<endl;
exit(0);
}
return list[i];
}
int main()
{
SeqList mylist(100);
int i,a[]={6,8,16,2,34,56,7,10,22,45};
for(i=0;i<10;i++)
mylist.ListInsert(a[i],i);
cout<<"插入后顺序表";
mylist.ListTraverse();
mylist.ListDelete(4);
cout<<"删除后顺序表";
mylist.ListTraverse();
return 0;
}