数据结构 集合合并与有序表合并

实验内容(教材 严蔚敏著)

1.用顺序表和链表分别分别编程实现教材中例子2-1与2-2。要求:

完全保持书中算法2.1 Union 与算法2.2MergeLis 形式,不允许有任何变化,除非语法上不允许;所调用各函数参照书中19页的功能描述,其中函数名、参数个数及性质、函数功能必须与书中完全一致,不能有变化。

Union 功能:

void Union(SqList *La,SqList Lb)
 { /* 将所有在表Lb中但不在La中的数据元素插入到La中 */
   ElemType e;
   int La_len,Lb_len;
   int i;
   La_len=ListLength(La); /* 求表La的长度 */
   Lb_len=ListLength(&Lb);/* 求表Lb的长度 */
   
   for(i=1;i<=Lb_len;i++)
   {
     GetElem(Lb,i,&e); /* 取Lb中第i个数据元素赋给e */
     if(!LocateElem(*La,e,equal))/* La中不存在和e相同的元素,则插入之 */
       ListInsert(La,++La_len,e);
   }
 }

集合合并所有功能函数:

void Union(SqList *La,SqList Lb);/* 将所有在表Lb中但不在La中的数据元素插入到La中 */
Status ListEmpty(SqList L);/* 判断表L是否为空 */ 
Status GetElem(SqList L,int i,ElemType *e);/* 得到表L的第i个元素并赋值给e */
Status CreatSqList(SqList *L,int len);/* 创建长度为len的一个线性表 */ 
int ListLength(SqList *L);/* 返回得到表L的长度 */ 
Status InitList(SqList *L);/* 初始化一个动态数组 */
Status DestroyList(SqList L);/* 销毁线性表L */
Status ClearList(SqList *L);/* 将线性表L重置为空表 */

int LocateElem(SqList L,int e,Status (*compare)(ElemType,ElemType)) ;
Status equal(int a,int b); 

Status ListInsert(SqList *L,int i,ElemType e);/* 在顺序表L第i个位置插入元素e */ 
void print(SqList L);/* 打印 */

所有功能实现:

#include<stdio.h>
#include<stdlib.h>

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
//#define MAXSIZE 50          /* 存储空间初始分配量 */
#define LIST_INIT_SIZE 100 /* 线性表存储空间的始分配量量*/ 
#define LISTINCREMENT 10 /* 线性表存储空间的分配增量*/ 
//Status 为函数的类型,其值是函数结果状态代码,如OK等
typedef int Status; 

// ElemType为数据元素类型,根据实际情况而定,这里假设为int 
typedef int ElemType;  

typedef struct
{
   
	ElemType *elem;  /* 存储空间基址 */
	int length;              /* 表当前有效长度 */
	int listsize;	/* 当前的分配存储容量(以sizeof(ElemType)为基本单位)*/ 
}SqList;   


int main() 
{
   
	SqList La,Lb;
	int La_len,Lb_len;
	printf("请分别输入La和Lb的数组长度:");
	scanf("%d %d",&La_len,&Lb_len);
	CreatSqList(&La,La_len);
	CreatSqList(&Lb,Lb_len);
	
	Union(&La,Lb);
	print(La);
	
	return 0; 
} 
Status CreatSqList(SqList *L,int len)
{
   
	InitList(L);/* 初始化 */
	L->length = len;
	
	if(len > L->listsize)/* 当前存储空间已满,增加分配*/
	{
   
		L->elem = (ElemType *)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(ElemType));
	} 
	if(!L
  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值