数据结构 | 顺序有序表的合并的实现

参考书籍:《数据结构(第2版)》严蔚敏

在这里插入图片描述

  • 代码
#include<iostream>
using namespace std;

#define MAXSIZE 100
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;

//结构体定义
typedef struct
{
	ElemType *data;
	int length;
 } SqList;

//初始化
Status InitList(SqList &L)
{
	L.data = new ElemType[MAXSIZE];
	if(!L.data)  exit(OVERFLOW);
	L.length = 0;
	return OK;
}

//获得表长
int List_length(SqList L)
{
	return L.length;
}

//表L的第i个位置插入元素e
Status ListInsert(SqList &L,int i,ElemType e)
{
	if((i<1) || (i>L.length+1))  return ERROR;   //位置不合法 
	if(L.length == MAXSIZE)      return ERROR;   //表已满
	for(int j=L.length-1; j>=i-1; j--)
	{
		L.data[j+1] = L.data[j];
	} 
	L.data[i-1] = e;
	++L.length;   //表长加1 
	return OK;
	 
} 

void Merge_List(SqList LA,SqList LB,SqList &LC)
{
	LC.length = LA.length + LB.length;
	ElemType *pa,*pb,*pc,*pa_last,*pb_last;
	pa = LA.data;
	pb = LB.data;
	pc = LC.data;
	pa_last = pa + LA.length-1;
	pb_last = pb + 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++;	
}


void PrintList(SqList L)
{
	int j;
	for(j=1;j<=L.length;j++)
	    cout << L.data[j-1] << " ";
}


int main()
{
	SqList LA,LB,LC;
	InitList(LA);InitList(LB);InitList(LC);
	
	ListInsert(LA,1,3);
	ListInsert(LA,2,5);
	ListInsert(LA,3,8);
	ListInsert(LA,4,11);
	ListInsert(LB,1,2);
	ListInsert(LB,2,6);
	ListInsert(LB,3,8);
	ListInsert(LB,4,9);
	ListInsert(LB,5,11);
	ListInsert(LB,6,15);
	ListInsert(LB,7,20);
	
	cout << "当前线性表LA的长度为:" << List_length(LA) <<endl;	
	cout << "当前表LA的元素为:";
	PrintList(LA);
	cout << endl;
	
	cout << "当前线性表LB的长度为:" << List_length(LB) <<endl;
	cout << "当前表LB的元素为:";
	PrintList(LB);
	cout << endl;
	
	Merge_List(LA,LB,LC);
	int a=List_length(LC);
	cout << "表LC的长度:" << a <<endl; 
	cout << "表LC的元素为:";
	PrintList(LC);		
}
  • 运行结果
    在这里插入图片描述
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值