第三週 項目3-求集合並集

list.h 代碼:

/*  
*Copyright (c) 2017,煙臺大學計算機與控制工程學院  
*All rights reserved.  
*文件名稱:  
*作    者:陳軍正  
*完成日期:2017年9月20日  
*版 本 號:v1.0  
*  
*問題描述:假設有兩個集合A和B分別用兩個線性表LA和LB表示,即線性表中的數據元素即爲集合中的成員。
*設計算法,用函數unionList(ListLA,ListLB,List&LC)函數實現該算法,
*求一個新的集合C=A∪B,即將兩個集合的並集放在線性表LC中。
*/ 

#ifndef LIST_H_INCLUDEDbool ListInsert(SqList *&L,int i,ElemType e)
#define LIST_H_INCLUDED
#define MaxSize 50
typedef struct
{
    int data [MaxSize];
    int length;
}SqList;

void CreateList(SqList *&,int [],int );
void DispList(SqList *&);
void Add (SqList *&L1,SqList *&L2,SqList *&L);
#endif // LIST_H_INCLUDED

main.cpp 代碼:

#include <iostream>
#include "list.h"
using namespace std;
int main ()
{
    int x[3] = {1,2,3};
    int y[3] = {4,5,6};
    int z[6] = {0,0,0,0,0,0};
    SqList *sq1,*sq2,*sq;
    CreateList(sq1,x,3);
    CreateList(sq2,y,3);
    CreateList(sq,z,6);
    cout<<"第一個集合:";
    DispList(sq1);
    cout<<endl<<"第二個集合:";
    DispList(sq2);
    Add (sq1,sq2,sq);
    cout<<endl;
    DispList(sq);
    return 0;
}


list.cpp 代碼:

#include "malloc.h"
#include "list.h"
#include <iostream>
using namespace std;
void CreateList(SqList *&L,int 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 DispList(SqList *&L)
{
    int i;
    for(i=0;i<L->length;i++)
    {
        cout<<L->data[i]<<" ";
    }
}

void Add (SqList *&L1,SqList *&L2,SqList *&L)
{
    int i,q;
    for (i = 0;i<L1->length;i++)
        L->data[i] = L1->data[i];
    for (q=0;q<L2->length;q++,i++)
        L->data[i] = L2->data[q];
}


運行結果:



知識點總結:調用我們早已經寫好的算法庫,可以省掉很多時間,這大大提高了我們敲代碼的效率,所以,注意自己早已寫的代碼的保存。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章