#include using namespace std; #include #define LIST_INIT_SIZE 100 #define LIST_INCREASE 20 #define OVERFLOW 0 #define ERROR 0 #define OK 1 typedef int Status; typedef struct { int *elem; int length; int listsize; }SqList; Status InitSq(SqList &L)//构造一个空的线性表 { L.elem=(int *)malloc(LIST_INIT_SIZE*sizeof(int)); if(!L.elem) return OVERFLOW; L.length=0; L.listsize=LIST_INIT_SIZE; return OK; } Status InsertSq(SqList &L,int i,int e)//在顺序线性表 L 中第 i 个位置之前插入新的元素 e { int *newbase; int *p,*q; if(i<1||i>L.length+1) return ERROR; if(L.length>=L.listsize) { newbase=(int *)realloc(L.elem,(L.listsize+LIST_INCREASE)*sizeof(int)); if(!L.elem) return OVERFLOW; L.elem=newbase; L.listsize=L.listsize+LIST_INCREASE; } q=&(L.elem[i-1]); for(p=&(L.elem[L.length-1]);p>=q;--p) *(p+1)=*p; *q=e; ++L.length; return OK; } Status DeleteSq(SqList &L,int i,int &e)//在顺序线性表 L 中删除第 i 个元素 { int *p,*q; if(i<1||i>L.length) return ERROR; p=&(L.elem[i-1]); e=*p; q=L.elem+L.length-1; for(++p;p<=q;++p) *(p-1)=*p; --L.length; return OK; } Status MergeSq(SqList L1,SqList L2,SqList &L3)//合并顺序表 { int *p1,*p2,*p3; int *p1_last,*p2_last; p1=L1.elem; p2=L2.elem; L3.length=L1.length+L2.length; L3.listsize=L3.length; L3.elem=(int *)malloc(L3.listsize*sizeof(int)); p3=L3.elem; if(!L3.elem) return OVERFLOW; p1_last=p1+L1.length-1; p2_last=p2+L2.length-1; while(p1<=p1_last && p2<=p2_last) { if(*p1<=*p2) *p3++=*p1++; else *p3++=*p2++; } while(p1<=p1_last) *p3++=*p1++; while(p2<=p2_last) *p3++=*p2++; return OK; } void CreatSq(SqList &L,int n)//创建顺序表 { int i,e; cout<<"请输入顺序表的数据元素: "; for(i=0;i>e; L.elem[i]=e; L.length=i+1; } } void ShowSq(SqList &L)//输出顺序表 { int j,k; int i=L.length; cout<<"顺序表如下: "; for(j=0;j"; } if(j==i-1 && i>0) { k=L.elem[j]; cout<>n; CreatSq(L,n); ShowSq(L); //顺序表的插入 cout<<"请输入被插入元素的位置: "; cin>>i; cout<<"请输入被插入的数据元素: "; cin>>e; InsertSq(L,i,e); ShowSq(L); //顺序表的删除 cout<<"请输入被删除元素的位置: "; cin>>i; DeleteSq(L,i,e); ShowSq(L); //顺序表的合并 SqList L1,L2,L3; InitSq(L1); InitSq(L2); int r,s; cout<<"请输入两个顺序表的长度分别为: "; cin>>r>>s; CreatSq(L1,r); CreatSq(L2,s); MergeSq(L1,L2,L3); ShowSq(L3); return 0; }