将两个有序顺序表A和B归并为一个有序顺序表C
#include<iostream.h> #include<stdlib.h> #define LIST_INIT_SIZE 100 #define OK 1 #define OVERFLOW -2 #define ERROR 0 typedef int Status; typedef int ElemType; typedef struct { ElemType *elem; int length; //当前长度 int listsize; //当前分配的存储容量 }SqList; Status InitList_Sq(SqList &L) { //构造一个空的线性表 L.elem=new ElemType[LIST_INIT_SIZE]; if(!L.elem) exit(OVERFLOW); L.length=0; L.listsize=LIST_INIT_SIZE; return OK; }//InitList_Sq Status ListCreate_Sq(SqList &L,int n) { //创建顺序表 //i的合法范围为 1<=i<=L.length+1 ElemType x; cout<<"input x(n)="<<endl; for(int i=1;i<=n;++i) { cin>>x; L.elem[i-1]=x; ++L.length; } return OK; }//ListCreat_Sq void Merge_Sq(SqList &LC,SqList LA,SqList LB) { //将两个有序表LA,LB合并成一个有序表LC int i=0,j=0,k=0; LC.length=LA.length+LB.length; while((i<LA.length)&&(j<LB.length)) if(LA.elem[i]<=LB.elem[j]) { LC.elem[k]=LA.elem[i]; i++,k++; } else { LC.elem[k]=LB.elem[j]; j++;k++; } while(i<LA.length) { LC.elem[k]=LA.elem[i]; i++,k++; } while(j<LB.length) { LC.elem[k]=LB.elem[j]; j++,k++; } }//Merge_Sq void print(SqList L) { int i; for(i=1;i<=L.length;++i) cout<<L.elem[i-1]<<" "; cout<<endl; } void main() { SqList LA,LB,LC; InitList_Sq(LA); cout<<"create LA\n"<<endl; ListCreate_Sq(LA,4); cout<<"output LA\n"<<endl; print(LA); cout<<endl; InitList_Sq(LB); cout<<"create LB\n"<<endl; ListCreate_Sq(LB,7); cout<<"output LB\n"<<endl; print(LB); InitList_Sq(LC); Merge_Sq(LC,LA,LB); cout<<"output LC\n"<<endl; print(LC); }