您的位置:首页 > 其它

第三周-项目3求集合并集

2015-10-20 11:21 204 查看
#include<iostream>

#include<malloc.h>

using namespace std;

#define MaxSize 50

typedef int ElemType;  //ElemType在不同场合可以根据问题的需要确定,在此取简单的int

typedef struct

{

    ElemType data[MaxSize];  //利用了前面MaxSize和ElemType的定义

    int length;

} SqList;

int ListLength(SqList *L);

void InitList(SqList *&L) ;

void CreateList(SqList *&L, ElemType a[], int n);

void unionList(SqList *LA, SqList *LB, SqList *&LC );

bool GetElem(SqList *L,int i,ElemType &e);

bool ListInsert(SqList *&L,int i,ElemType e);

bool ListEmpty(SqList *L);

int LocateElem(SqList *L,ElemType e);

int main()

{

 SqList *sq1,*sq2,*sq3;

 ElemType a[6]={5,7,4,8,3,1};

 ElemType b[6]={11,14,16,25,58,19};

 CreateList(sq1,a,6);

 CreateList(sq2,b,6);

 InitList(sq3);

 unionList(sq1,sq2,sq3);

 return 0;

}

void unionList(SqList *LA, SqList *LB, SqList *&LC )

{

 int lena,i;

 ElemType e;

 

 for(i=0;i<=ListLength(LA);i++)

 {

  GetElem(LA,i,e);

  ListInsert(LC,i,e);

 }

 lena=ListLength(LA);

    for(i=1;i<=ListLength(LB);i++)

 {

  GetElem(LB,i,e);

  if(LocateElem(LA,e)==0)

   ListInsert(LC,++lena,e);

 }

 for(i=0;i<ListLength(LC);i++)

 {

  cout<<LC->data[i]<<" ";

 }

 cout<<endl;

 cout<<ListLength(LC)<<endl;

 

}

void InitList(SqList *&L)   //引用型指针

{

    L=(SqList *)malloc(sizeof(SqList));

    //分配存放线性表的空间

    L->length=0;

}

void CreateList(SqList *&L, ElemType a[], int n)

{

  int i;

    L=(SqList *)malloc(sizeof(SqList));

    for (i=0; i<n; i++)

        L->data[i]=a[i];

    L->length=n;

}

bool GetElem(SqList *L,int i,ElemType &e)

{

    if (i<1 || i>L->length)  return false;

    e=L->data[i-1];

    return true;

}

bool ListInsert(SqList *&L,int i,ElemType e)

{

    int j;

    if (i<1 || i>L->length+1)

        return false;   //参数错误时返回false

    i--;            //将顺序表逻辑序号转化为物理序号

    for (j=L->length; j>i; j--) //将data[i..n]元素后移一个位置

        L->data[j]=L->data[j-1];

    L->data[i]=e;           //插入元素e

    L->length++;            //顺序表长度增1

    return true;            //成功插入返回true

}

bool ListEmpty(SqList *L)

{

    return(L->length==0);

}

int ListLength(SqList *L)

{

    return(L->length);

}

int LocateElem(SqList *L,ElemType e)

{

 int i,shuju;

 for(i=0;i<ListLength(L);i++)

 {

  GetElem(L,i,shuju);

  if(shuju==e) return 1;

 }

 return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: