/*
顺序表实现的集合的交、并、插入、删除
*/
#define LISTSIZE 15
#define LISTINCREMENT 8
#include<stdio.h>
#include<stdlib.h>
struct SqList{
int *elem;
int length;
int listsize;
};
void InitList(SqList &l){
l.elem=(int*)malloc(sizeof(int)*LISTSIZE);
if(!l.elem){
printf("Overflow");
exit(1);
}
l.length=0;
l.listsize=LISTSIZE;
}
void ClearList(SqList &l){
l.length=0;
}
void DestoryList(SqList &l){
free(l.elem);
l.elem=NULL;
l.length=0;
l.listsize=0;
}
int ListLength(SqList l){
return l.length;
}
bool SqListEmpty(SqList l){
return l.length==0;
}
void GetElem(SqList l,int i,int &e){
if(i<1&&i>l.length) {
printf("越界查找元素");
exit(1);
}else
e=l.elem[i-1];
}
int LocateElem(SqList l,int e){
int i;
for(i=1;i<=l.length;i++)
if(l.elem[i-1]==e) return i;
return 0;
}
void PriorElem(SqList l,int cur_e,int &prior_e){
int i=LocateElem(l,cur_e);
if(i==0){
printf("元素%3d不存在顺序表中\n",cur_e);
exit(1);
}else if(i==1){
printf("元素%3d为首元素,不存在前驱元素",cur_e);
exit(1);
}
prior_e=l.elem[i-1];
}
void NextElem(SqList l,int cur_e,int &next_e){
int i=LocateElem(l,cur_e);
if(i==0){
printf("元素%3d不存在顺序表中\n",cur_e);
exit(1);
}else if(i==l.length){
printf("元素%3d为尾元素,不存在后继元素",cur_e);
exit(1);
}
next_e=l.elem[i+1];
}
void ListInsert(SqList &l,int i,int e){
if(i<1||i>l.length+1) {
printf("插入的元素越界");
return;
}
if(l.length>=l.listsize){
l.elem=(int *)realloc(l.elem,sizeof(int)*(LISTSIZE+LISTINCREMENT));
if(!l.elem){
printf("overflow");
exit(1);
}
l.listsize+=LISTINCREMENT;
}
int *q=l.elem+i-1;
for(int *p=l.elem+l.length-1;p>=q;p--)
*(p+1)=*p;
*q=e;
l.length++;
}
void ListDelete(SqList &l,int i,int &e){
if(i<1||i>l.length){
printf("删除元素越界\n");
return;
}
int *p,*q;
q=l.elem+l.length-1;
for(p=l.elem+i-1;p<=q;p++)
*p=*(p+1);
l.length--;
}
//并集
void Union(SqList &la,SqList lb){
int i,e;
int la_len=ListLength(la);
int lb_len=ListLength(lb);
for(i=1;i<=lb_len;i++){
GetElem(lb,i,e);
if(!LocateElem(la,e)) ListInsert(la,++la_len,e);
}
}
void MergeList(SqList la,SqList lb,SqList &lc){
int la_len=la.length;
int lb_len=lb.length;
int *pa=la.elem;
int *pa_last=la.elem+la_len-1;
int *pb=lb.elem;
int *pb_last=lb.elem+lb_len-1;
lc.listsize=lc.length=la_len+lb_len;
lc.elem=(int*)malloc(sizeof(int)*lc.length);
int *pc=lc.elem;
if(!lc.elem){
printf("overflow");
exit(1);
}
while(pa<=pa_last&&pb<=pb_last){
if(*pa<*pb) *pc++=*pa++;
else if(*pa>*pb) *pc++=*pb++;
else{
*pc++=*pa;
pa++;
pb++;
}
}
while(pa<=pa_last) *pc++=*pa++;
while(pb<=pb_last) *pc++=*pb++;
lc.length=pc-lc.elem;
}
void Print(SqList l){
for(int i=1;i<=l.length;i++)
printf("%3d",l.elem[i-1]);
printf("\n");
}
void main()
{
int i,j;
SqList la,lb,lc;
InitList(la);
for(i=1;i<=10;i++)
ListInsert(la,i,i);
Print(la);
InitList(lb);
for(i=1;i<=15;i++)
ListInsert(lb,i,2*i);
Print(lb);
//MergeList(la,lb,lc);
MergeList(la,lb,lc);
Print(lc);
Union(la,lb);
Print(la);
}
顺序表基本操作
最新推荐文章于 2022-09-25 15:14:48 发布