首页 > 其他 > 详细

2.1 Sequence List

时间:2020-03-08 11:11:10      阅读:47      评论:0      收藏:0      [点我收藏+]
#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);
    }
};

main:

#include"SeqList.h"

int main() {
    SeqList<int> L(200);
    cout << "创建成功,最大容量为: " << L.Size() <<",长度:"<<L.Length()<< endl;
    for (int i = 9; i >= 1; i--) {
        L.Insert(0, i);
    }
    cout << "插入成功:" << endl;
    cout <<"长度:" << L.Length() << endl;
    L.show();
    cout << "7的序号是:" << L.Search(7) << endl;
    int a;
    L.getData(5,a);
    cout << "序号5对应的元素是:" << a << endl;
    L.Remove(3, a);
    cout << "删除了序号是3的元素:" << a << endl;
    L.show();
    return 0;
}

display:

技术分享图片

2.1 Sequence List

原文:https://www.cnblogs.com/SlowIsFast/p/12441202.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!