两个有序顺序表合并成一个有序顺序表
程序员文章站
2024-03-08 23:10:34
...
一 概述
将两个有序顺序表合并为一个新的有序表,并由函数返回结果顺序表。实际过程中应该不断取下两个顺序表表头较小的结点存在新的顺序表中,然后,将其中某个表中的剩余数据直接加到新的顺序表后面。
二 代码实现
/*合并两个有序顺序表*/
#include <iostream>
using namespace std;
typedef int ElemType;
#define MAXSIZE 100
#define ERROR 0
#define OK 1
typedef struct {
ElemType *elem;
int length;
}SqList;
int InitOrderList(SqList &L1,SqList &L2,SqList &L3){
L1.elem = new ElemType[MAXSIZE];
L2.elem = new ElemType[MAXSIZE];
L3.elem = new ElemType[MAXSIZE];
if(!L1.elem || !L2.elem || !L3.elem){
return ERROR;
}
return OK;
}
int MargeOrderList(SqList L1,SqList L2,SqList &L3){
if(L1.length + L2.length > L3.length){
return false;
}
int i=0,j=0,k=0;
while (i < L1.length && j < L2.length){
if(L1.elem[i] <= L2.elem[j]) {
L3.elem[k++] = L1.elem[i++];
}else {
L3.elem[k++] = L2.elem[j++];
}
}
while (i < L1.length) {
L3.elem[k++] = L1.elem[i++];
}
while (j < L2.length) {
L3.elem[k++] = L2.elem[j++];
}
L3.length = k;
return OK;
}
int main(){
SqList L1,L2,L3;
int select = -1,i;
cout<<"将两个有序表合并成一个有序表!"<<endl;
cout<<"1.初始化有序线性表!"<<endl;
cout<<"2.插入6个数到有序表L1!"<<endl;
cout<<"3.插入7个数到有序表L2!"<<endl;
cout<<"4.将有序表L1和L2合并到L3!"<<endl;
cout<<"0.退出!"<<endl;
while(select != 0){
cout<<"请选择:";
cin>>select;
switch(select){
case 1:
if(InitOrderList(L1,L2,L3)){
cout<<"有序表初始化成功!"<<endl ;
}else{
cout<<"有序表初始化失败!"<<endl;
}
break;
case 2:
for(i = 0; i < 6; i++) {
cin>>L1.elem[i];
}
L1.length = 6;
break;
case 3:
for(i = 0; i < 7; i++) {
cin>>L2.elem[i];
}
L2.length = 7;
break;
case 4:
MargeOrderList(L1,L2,L3);
for(i = 0; i < L3.length; i++){
cout<<L3.elem[i]<<" ";
}
cout<<endl;
break;
}
}
return 0;
}
三 结果
上一篇: javaIO流的学习笔记
下一篇: Mybatis与Hibernate的区别