线性表的顺序存储结构 顺序表(sequential list)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baishuiniyaonulia/article/details/82731315

类定义

SeqList.h

#ifndef __SEQLIST_H__
#define __SEQLIST_H__

template<class T>
class SeqList
{
public:
    SeqList();
    SeqList(T *_data, int _length);
    virtual ~SeqList();

public:
    int getLength();
    void Insert(int _pos, T _data);
    T Delete(int _pos);
    void setElement(int _pos, T _data);
    T getValue(int _pos);
    int getLocation(T _data);
    void Traverse();

private:
    static const int MaxSize = 100;
    T data[MaxSize];
    int length;
};

#endif // !__SEQLIST_H__

类实现

SeqList.cpp

#include <iostream>
#include "SeqList.h"
using namespace std;

/* Constructor && Distructor */
template <class T>
SeqList<T>::SeqList()
{
    length = 0;
}

template <class T>
SeqList<T>::SeqList(T *_data, int _length)
{
    if (_length > MaxSize || _length < 0)
        throw "Illegal Length";
    else
    {
        length = _length;
        for (int i = 0; i < length; i++)
            data[i] = *(_data + i);
    }
}

template <class T>
SeqList<T>::~SeqList()
{
}

/* Operating Function */
template <class T>
int SeqList<T>::getLength()
{
    return length;
}

template <class T>
void SeqList<T>::Insert(int _pos, T _data)
{
    if (_pos > length || _pos < 0)
        throw "Illegal Posistion";
    for (int i = length; i >= _pos; i--)
        data[i] = data[i - 1];
    data[_pos - 1] = _data;
    length += 1;
}

template <class T>
T SeqList<T>::Delete(int _pos)
{
    T tempData = data[_pos];

    if (_pos > length || _pos <= 0)
        throw "Illegal Posistion";
    for (int i = _pos - 1; i < length - 1; i++)
        data[i] = data[i + 1];
    length -= 1;

    return tempData;
}

template <class T>
void SeqList<T>::setElement(int _pos, T _data)
{
    if (_pos > length || _pos < 0)
        throw "Illegal Posistion";

    data[_pos - 1] = _data;
}

template <class T>
T SeqList<T>::getValue(int _pos)
{
    if (_pos > length || _pos < 0)
        throw "Illegal Posistion";
    else
        return data[_pos - 1];
}

template <class T>
int SeqList<T>::getLocation(T _data)
{
    for (int i = 0; i < length; i++)
        if (data[i] == _data)
            return i + 1;
}

template <class T>
void SeqList<T>::Traverse()
{
    for (int i = 0; i < length; i++)
        cout << data[i] << " ";
    cout << endl;
}

类测试

Sequential.cpp

#include <iostream>
#include "SeqList.h"
#include "SeqList.cpp"
using namespace std;

int main()
{
    int arr[5] = { 0, 0, 0, 0, 0 };
    SeqList<int> list(arr, 5);

    list.Traverse();

    list.Insert(1, 1);
    list.Traverse();

    list.Delete(1);
    list.Traverse();

    list.setElement(2, 2);
    list.Traverse();

    cout << list.getValue(2) << endl;
    cout << list.getLocation(2) << endl;
    cout << list.getLength() << endl;

    return 0;
}

输出结果:

0 0 0 0 0
1 0 0 0 0 0
0 0 0 0 0
0 2 0 0 0
2
2
5

猜你喜欢

转载自blog.csdn.net/baishuiniyaonulia/article/details/82731315