2.1 顺序表实现集合的“交”运算

SeqList.h 

#pragma once
#include <iostream>           //定义在“seqList.h”中
#include <stdlib.h>
using namespace std;
const int defaultSize = 100;
template < class E>
class SeqList {
protected:
    E* data;             //存放数组
    int maxSize;         //最大可容纳表项的项数
    int last;             //当前已存表项的最后位置
    //void reSize(int newSize);    //改变数组空间大小
public:
    SeqList(int sz = defaultSize) {
        maxSize = sz;
        data = new E[maxSize];
        last = -1;
    }
    //构造函数
    SeqList(SeqList<E>& L) {
        this->maxSize = L.maxSize;
        this->last = L.last;
        this->data = new E[maxSize];
        for (int i = 0; i <= last; i++) {
            this->data[i] = L.data[i];
        }
    }
    //复制构造函数

    int Size() const {
        return maxSize;
    }
    //求表最大容量
    int Length() const {
        return last + 1;
    }
    //计算表长度
    int Search(E x) const
    {
        E e = x;
        int ret = -1;
        for (int i = 0; i <= last; i++)
        {
            if (data[i] == e) {
                ret = i;
                break;
            }
        }
        return ret;
    }
    //搜索x在表中位置,函数返回表项序号
    int Locate(int i) const {
        if (i >= 1 && i <= last + 1) {
            return --i;
        }
        else {
            return -2;
        }
    }
    //定位第 i 个表项,函数返回表项序号
    bool getData(int i, E& x) const {
        x = data[i];
        return true;
    }
    //取第i个表项的值
    bool Insert(int i, E x) {
        for (int j = last; j >= i; j--) {
            data[j + 1] = data[j];
        }
        data[i] = x;
        last++;
        return true;
    }
    //插入
    bool Remove(int i, E& x) {
        x = data[i];
        for (int j = i; j < last; j++) {
            data[j] = data[j + 1];
        }
        last--;
        return true;
    }
    //删除
    void show() {
        for (int i = 0; i <= last; i++) {
            cout << data[i] << "  ";
        }
        putchar('\n');
    }
};

MyKit.h

#pragma once
#include"SeqList.h"
template<class T>
class MyKit
{
public:
    static void intersect(SeqList<T>& La, SeqList<T>& Lb) {
        int lastA = La.Length() - 1;
        int lastB = Lb.Length() - 1;
        T e;
        for (int i = 0; i <= lastA; i++) {
            La.getData(i, e);
            if (Lb.Search(e) < 0) {
                La.Remove(i, e);
            }
        }
    }
};

main.cpp

#include"MyKit.h"

int main()
{
    SeqList<int> L1, L2;
    L1.Insert(0, 9);
    L1.Insert(0, 6);
    L1.Insert(1, 3);
    cout << "L1:" << endl;
    L1.show();
    for (int i = 0; i <= 9; i++) {
        L2.Insert(0, i);
    }
    cout << "L2:" << endl;
    L2.show();
    MyKit<int>::intersect(L1, L2);
    cout << "Interscet:" << endl;
    L1.show();

}

 

posted @ 2020-03-08 19:40  落地就是一把98K  阅读(416)  评论(0)    收藏  举报