#include <iostream>
using namespace std;
#define MaxSize 1000
#define Crement 100
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
int listsize;
}Sqlist;
bool InitList(Sqlist &l) //初始化
{
l.elem=(ElemType *)malloc(MaxSize* sizeof(ElemType));
if(!l.elem)exit(EOVERFLOW);
l.length=0;
l.listsize=MaxSize;
return true;
}
bool CreateList(Sqlist &l)
{
cout<<"size: "<<endl;
size_t size;
cin>>size;
cout<<"contents:"<<endl;
bool InsertList(Sqlist&l,int i,ElemType elem);
for(auto i=0;i<size;i++)
{
ElemType temp;
cin>>temp;
InsertList(l,i,temp);
}
cout<<"create success"<<endl;
}
bool InsertList(Sqlist&l,int i,ElemType elem) //下标从0开始,完成后沟插入元素位于elem[i]
{
if(i<0||i>l.length)return false;
if(l.length>=l.listsize)
{
auto newbase=(ElemType*)realloc(l.elem,(MaxSize+Crement)* sizeof(ElemType));
if(!newbase)exit(EOVERFLOW);
l.elem=newbase;
l.listsize+=Crement;
}
auto q=&(l.elem[i]);
for(auto p=&(l.elem[l.length-1]);p>=q;p--)*(p+1)=*p;
*q=elem;
l.length++;
return true;
}
bool DeleteList(Sqlist&l,ElemType&e,int pos)
{
if(pos<1||pos>l.length)return false;
auto p=&l.elem[pos];
e=*p;
for(p;p<l.elem+l.length;++p)*p=*(p+1);
l.length--;
}
bool MergeList(Sqlist la,Sqlist lb,Sqlist &lc) //合并有序线性表
{
auto pa=la.elem;
auto pb=lb.elem;
lc.length=lc.listsize=la.length+lb.length;
auto pc=lc.elem=(ElemType*)malloc(lc.listsize* sizeof(ElemType));
if(!pc)exit(EOVERFLOW);
while(pa<=la.elem+la.length-1&&pb<=lb.elem+lb.length-1)
{
if(*pa<*pb)*pc++=*pa++; //前置++和后置++在参与赋值运算时的区别
else *pc++=*pb++;
}
while(pa<=la.elem+la.length-1)*pc++=*pa++;
while(pb<=lb.elem+lb.length-1)*pc++=*pb++;
}
bool (*compare)(ElemType,ElemType); //函数指针,nice
bool Isequal(ElemType a,ElemType b)
{
return a==b;
}
int LocateElem(Sqlist l,ElemType e,bool (*compare)(ElemType,ElemType))
{
compare=Isequal;
for(int i=0;i<l.length;i++)
{
if((*compare)(l.elem[i],e))return i;
}
return -1;
}
void PrintList(Sqlist l)
{
for (unsigned int i=0;i<l.length;i++) {
cout<<l.elem[i]<<" ";
}
}
//class List{
//public:
//
//};
int main() {
Sqlist l;
Sqlist l1;
InitList(l);
Sqlist templ;
//InitList(l1);
ElemType e;
int pos;
unsigned int choice=7;
while(choice) {
cout<<endl<<"***0:exit***1:create***2:insert***3:delete***4:locate***5:merge***6:print***"<<endl;
cin>>choice;
while(choice<0||choice>6){
cout<<"error, input again"<<endl;
cin>>choice;
}
switch (choice) {
case 0:break;
case 1:
CreateList(l);
break;
case 2:
cin>>e;
cin>>pos;
InsertList(l,pos,e);
break;
case 3:
cout<<"***1:delete_by_pos***2:delete_by_cont***"<<endl;
cin>>choice;
if(choice==1)
{
cout<<"pos:"<<endl;
cin>>pos;
DeleteList(l,e,pos);
cout<<"delete element: "<<e<<endl;
}
if(choice==2)
{
cout<<"content:"<<endl;
cin>>e;
while(LocateElem(l,e,compare)>=0)
DeleteList(l,e,LocateElem(l,e,compare));
}
break;
case 4:
cin>>e;
cout<<"pos: "<<LocateElem(l,e,compare)<<endl;
break;
case 5:
InitList(templ);
templ=l;
InitList(l1);
CreateList(l1);
MergeList(templ,l1,l);
break;
case 6:
PrintList(l);
break;
}
}
return 0;
}
顺序表
最新推荐文章于 2022-03-21 17:14:08 发布