#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define kd 100 //动态数组的大小
#define zj 10 //需要增加的大小
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType *elem;
int length;
int listsize;
}sqlist; //定义一个链表
Status f1(sqlist &L,int n) //f1初始化链表
{
L.elem=(ElemType *)malloc(kd*sizeof(ElemType));
if(!L.elem) return -2;
for(int i=0;i<n;i++)
cin>>L.elem[i];
L.length=n;
L.listsize=kd;
return 1;
}
Status f2(sqlist &L,int i,ElemType e)//在i位置插入e
{
if(i<1||i>L.length+1) return 0;
if(L.length>=L.listsize)
{
ElemType *newbase=(ElemType *)realloc(L.elem,(L.listsize+zj)*sizeof(ElemType));
if(!newbase) return -2;
L.elem=newbase;
L.listsize+=zj;
}
ElemType *q=&(L.elem[i-1]);
for(ElemType *p=&(L.elem[L.length-1]);p>=q;--p)
*(p+1)=*p;
*q=e;
++L.length;
return 1;
}
Status f3(sqlist &L,int i,ElemType e) //f3删除i位置的数
{
if(i<1||i>L.length) return 0;
ElemType *p=&(L.elem[i-1]);
e=*p;
ElemType *q=&(L.elem[L.length-1]);
for(++p;p<=q;++p)
*(p-1)=*p;
--L.length;
return e;
}
Status f4(sqlist La,sqlist Lb,sqlist &Lc) //f4实现归并
{
ElemType *pa=La.elem;
ElemType *pb=Lb.elem;
Lc.listsize=Lc.length=La.length+Lb.length;
ElemType *pc=Lc.elem=(ElemType *)malloc(Lc.listsize*sizeof(ElemType));
if(!Lc.elem) return -2;
ElemType *pa_last=&(La.elem[La.length-1]);
ElemType *pb_last=&(Lb.elem[Lb.length-1]);
while(pa<=pa_last&&pb<=pb_last)
{
if(*pa<=*pb) *(pc++)=*(pa++);
else *(pc++)=*(pb++);//实现链表的递增操作
}
while(pa<=pa_last) *pc++=*pa++;
while(pb<=pb_last) *pc++=*pb++;
return 1;
}
int main(int argc, char *argv[])
{
ElemType a,b,n,c,d;
sqlist L,La,Lb,Lc;
cin>>a>>b>>n;
f1(L,n); //初始化
f2(L,a,b); //线性表的插入
for(ElemType i=0;i<L.length;i++)
cout<<L.elem[i]<<" ";
cout<<endl;
ElemType e=f3(L,a,b); //删除
for(ElemType i=0;i<L.length;i++)
cout<<L.elem[i]<<" ";
cout<<endl;
cout<<e<<endl;
cin>>c>>d;
f1(La,c); //初始化
f1(Lb,d); //初始化
f4(La,Lb,Lc); //线性表的归并
for(ElemType i=0;i<Lc.length;i++)
cout<<Lc.elem[i]<<" ";
cout<<endl;
return 0;
}
数据结构_线性表
最新推荐文章于 2024-05-01 15:44:50 发布