第三周 求并集合集

/* 
* Copyright (c) 2015, 烟台大学计算机与控制工程学院 
* All rights reserved. 
* 文件名称:main.cpp,list.cpp,list.h 
* 作   者:于东林 
* 完成日期:2015年9月21日 
* 版本号:3.6.0  
* 问题描述:建立算法库,将复杂的程序分解到三个文件中,实现AUB的基本运算。
* 输入描述:无 
* 程序输出:线性表的结果 
*/

程序及代码:

#include<stdio.h>  
#include <malloc.h>  
#define MaxSize 50   
typedef int ElemType;  
typedef struct  
{  
    ElemType data[MaxSize];  
    int length;  
}SqList;  
  
void CreateList(SqList *&L,ElemType a[],int n);  
void InitList(SqList *&L);  
int ListLength(SqList *L);  
void DispList(SqList *L);  
bool GetElem(SqList *L,int i,ElemType &e);  
int LocateElem(SqList *L,ElemType e);  
bool ListInsert(SqList *&L,int i,ElemType e);  
void unionList(SqList *LA,SqList *LB,SqList *&LC);
#include "tt.h"   
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;  
}  
  
void InitList(SqList *&L)  
{  
    L=(SqList *)malloc(sizeof(SqList));  
    L->length=0;  
}  
int ListLength(SqList *L)  
{  
    return (L->length);  
}   
  
void DispList(SqList *L)  
{  
    int i;  
    for(i=0;i<L->length;i++)  
        printf("%d ",L->data[i]);  
    printf("\n");  
}  
bool GetElem(SqList *L,int i,ElemType &e)  
{  
    if(i<1||i>L->length)  
        return false;  
    e=L->data[i-1];  
    return true;  
}  
int LocateElem(SqList *L,ElemType e)  
{  
    int i=0;  
    while(i<L->length && L->data[i]!=e)  
        i++;  
    if(i>=L->length)  
        return 0;  
    else   
        return i+1;  
}  
bool ListInsert(SqList *&L,int i,ElemType e)  
{  
    int j;  
    if(i<1||i>L->length+1)  
        return false;  
    i--;  
    for(j=L->length;j>i;j--)  
        L->data[j]=L->data[j-1];  
    L->data[i]=e;  
    L->length++;  
    return true;  
}  
  
void unionList(SqList *LA, SqList *LB, SqList *&LC)  
{  
    int lena,i;  
    ElemType e;  
    InitList(LC);  
    for (i=1; i<=ListLength(LA); i++) //将LA的所有元素插入到Lc中   
    {  
        GetElem(LA,i,e);  
        ListInsert(LC,i,e);  
    }  
    lena=ListLength(LA);         //求线性表LA的长度   
    for (i=1; i<=ListLength(LB); i++)  
    {  
        GetElem(LB,i,e);         //取LB中第i个数据元素赋给e   
        if (!LocateElem(LA,e)) //LA中不存在和e相同者,插入到LC中   
            ListInsert(LC,++lena,e);  
    }  
}


 

#include "tt.h" 
 
int main()  
{  
    SqList *sq_a, *sq_b, *sq_c;  
    ElemType a[6]= {5,8,7,2,4,9};  
    CreateList(sq_a, a, 6);  
    printf("LA: ");  
    DispList(sq_a);    
    ElemType b[6]= {2,3,8,6,0};  
    CreateList(sq_b, b, 5);  
    printf("LB: ");  
    DispList(sq_b);  
    unionList(sq_a, sq_b, sq_c);  
    printf("LC: ");  
    DispList(sq_c);  
    return 0;  
}  


运行结果:

知识点及总结:

        充分体验出了算法的好处,将算法的应用得到实现。

学习心得:

        针对线性表,算法库的建立,让我明白许多关于链表的知识。

你可能感兴趣的:(第三周 求并集合集)