用类实现线性表完整程序
#include<iostream.h>#include<malloc.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100
#define LISTNCREMENT 10
class Sqlist
{
public:
void InitSList();
void InsertSList();
void DeleteSList();
void FindList();
protected:
int *elem;
int length;
int listsize;
};
/**************************创建线性表*******************/
void Sqlist::InitSList()
{
int i;
elem=(int*)malloc(LIST_INIT_SIZE*sizeof(int));
if(!elem)exit(0);
length=0;
listsize=LIST_INIT_SIZE;
cout<<"请输入表长:"<<endl;
cin>>length;
cout<<"表中的元素是:"<<endl;
for(i=0;i<length;i++)
cin>>elem[i];
}
/*************************删除元素************************/
void Sqlist::DeleteSList()
{
int *p,*q,i;
if((i<1)||(i>length))
cout<<"ERROR"<<endl;
p=&(elem[i-1]);
q=elem+length-1;
for(++p;p<=q;++p)
*(p-1)=*p;
--length;
cout<<"新的顺序表中的元素是:"<<endl;
for(i=0;i<length-1;i++)
cout<<elem[i]<<endl;
}
/*************************插入元素**********************/
void Sqlist::InsertSList()
{
int*newbase,i,e;
int *q,*p;
cout<<"请输入插入元素的位置i:"<<endl;
cin>>i;
cout<<"请输入插入的新元素e:"<<endl;
cin>>e;
if(i<1||i>length+1)
cout<<"error"<<endl;
if(length>=listsize)
{
newbase=(int*)realloc(elem,(listsize+LISTNCREMENT)*sizeof(int));
if(!newbase)exit(0);
elem=newbase;
listsize+=LISTNCREMENT;
}
q=&(elem[i-1]);
for(p=&(elem[length-1]);p>=q;--p)
*(p+1)=*p;
*q=e;
++length;
cout<<"新的顺序表中的元素是:"<<endl;
for(i=0;i<length+1;i++)
cout<<elem[i]<<endl;
}
/********************查找元素**************************/
void Sqlist::FindList()
{
int *p,e,i;
cout<<"请输入查找元素的位置:"<<endl;
cin>>i;
p=&(elem[i-1]);
e=*p;
cout<<"请输出该位置的元素:"<<endl;
cout<<e<<endl;
}
/***************************主函数**********************/
main()
{
int i,m,e;
Sqlist L;
L.InitSList();
cout<<"请选择:"<<endl;
cout<<"1:插入元素:"<<endl;
cout<<"2:删除元素:"<<endl;
cout<<"3:查找元素:"<<endl;
cin>>m;
switch(m)
{
case 1:
L.InsertSList();
break;
case 2:
cout<<"请输入删除元素的位置:"<<endl;
cin>>i;
L.DeleteSList();
break;
case 3:
L.FindList();
break;
default:
cout<<"ERROR"<<endl;
}
}