#include<stdio.h> #include<stdlib.h> #include<math.h> typedef int Status ; typedef int ElemType; #define OK 1 #define ERROR 0 #define LISTSIZE 10 #define ADDSIZE 2 typedef struct { ElemType *elem; int length; int listsize; }SqList; Status InitList(SqList *L) { (*L).elem=malloc(LISTSIZE*sizeof(ElemType)); if(!(*L).elem) exit(OVERFLOW); (*L).length=0; (*L).listsize=LISTSIZE; return OK; } Status GetElem(SqList L,int i,ElemType *e) { if(i<1||i>L.length) return ERROR; *e=*(L.elem+i-1); return OK; } Status ListInsert(SqList *L,int i,ElemType e) { ElemType *newbase,*p,*q; if(i<1||i>(*L).length+1) return ERROR; if((*L).length>=(*L).listsize) { newbase=(ElemType*)realloc((*L).elem,((*L).length+ADDSIZE)*sizeof(ElemType)); if(!newbase) exit(OVERFLOW); (*L).elem=newbase; (*L).listsize+=ADDSIZE; } p=(*L).elem+i-1; q=(*L).elem+(*L).length-1; while(p<=q) { *(q+1)=*q; --q; } *p=e; ++(*L).length; return OK; } int ListLength(SqList L) { return L.length; } Status LocateElem(SqList L,ElemType e,Status (*compare)(ElemType ,ElemType)) { int i=1; ElemType *p,*q; p=L.elem; q=L.elem+L.length-1; while(p<=q&&!compare(*p,e)) { ++p; ++i; } if(i<=L.length) return i; else return 0; } Status ListTraverse(SqList L,void(*visit)(ElemType)) { ElemType *p=L.elem; int i=1; while(i<=L.length) { visit(*p); ++p; ++i; } printf("\n"); return OK; } Status equal(ElemType c1,ElemType c2) { if(c1==c2) return 1; else return 0; } void Union(SqList *La,SqList Lb) { ElemType e; int i,La_len,Lb_len; La_len=ListLength(*La); Lb_len=ListLength(Lb); for(i=1;i<=Lb_len;i++) { GetElem(Lb,i,&e); if(!LocateElem(*La,e,equal)) ListInsert(La,++La_len,e); } } void print(ElemType c) { printf("%d ",c); } void main() { SqList La,Lb; int j; InitList(&La); for(j=1;j<=5;j++) ListInsert(&La,j,j); printf("La="); ListTraverse(La,print); InitList(&Lb); for(j=1;j<=5;j++) ListInsert(&Lb,j,2*j); printf("Lb="); ListTraverse(Lb,print); Union(&La,Lb); printf("new La="); ListTraverse(La,print); }
程序运行如下:
时间: 2024-09-28 23:45:19