1. 程式人生 > >線性表的具體操作

線性表的具體操作

題目描述 :

假設有兩個集合A和B,分別用兩個線性表LA和LB表示,即線性表中的資料元素為集合中的元素,利用線性表的基本運算設計一個演算法求一個新的集合C=AUB,即將兩個集合的並集放線上性表LC中。

題解:

先初始化線性表LC,即建立一個空的線性表LC,將LA的所有元素複製到LC中,然後掃描線性表LB,將LB中不屬於LA的元素插入到LC中,LA,LB,和LC均為SQList型別變數,假設SqList是一個已經實現了的線性表資料結構。

要點:

靈活運用線性表的基本運算

C++程式碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define MaxSize 50
typedef struct
{
    int data[MaxSize];
    int length;
} SqList;
void InitList(SqList *&L)   // 初始化
{
    L=(SqList *)malloc(sizeof(SqList));
    L->length=0;
}
void CreateList(SqList *&L,int a[],int n)  // 集合到線性表
{
    int i=0,k=0;
    L=(SqList *)malloc(sizeof(SqList));   //定義
    while(i<n)
    {
        L->data[k]=a[i];
        k++,i++;
    }
    L->length=k;
}
bool GetElem(SqList *L,int i,int &e)
{
    if(i<1||i>L->length)
        return false;
    e=L->data[i-1];
    return true;
}
int LocateElem(SqList *L,int 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,int 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 DispList(SqList *L)      //輸出
{
    for(int i=0; i<L->length; i++)
        printf("%d ",L->data[i]);
    printf("\n");
}
int ListLength(SqList *L)   //求線性表長度
{
    return (L->length);
}
void unionList(SqList *LA,SqList *LB,SqList *&LC)
{
    int lena,i;
    int e;
    InitList(LC);         //初始化LC
    for(i=1; i<=ListLength(LA); i++)    //複製LA到LC
    {
        GetElem(LA,i,e);
        ListInsert(LC,i,e);
    }
    lena=ListLength(LA);
    for(i=1; i<ListLength(LB); i++)     //查詢LB
    {
        GetElem(LB,i,e);
        if(!LocateElem(LA,e))
            ListInsert(LC,++lena,e);
    }
}
int main()
{
    int n,a[10],b[10];
    scanf("%d",&n);       // 輸入資料
    for(int i=0; i<n; i++)
        scanf("%d",&a[i]);
    for(int j=0; j<n; j++)
        scanf("%d",&b[j]);
    SqList *LA,*LB,*LC;    // 定義LA LB LC
    CreateList(LA,a,n);   
    CreateList(LB,b,n);
    unionList(LA,LB,LC);   // 具體實現
    DispList(LC);       // 輸出LC
    return 0;
}