顺序存储链表

  • 头文件
#pragma once

template 

class SeqList
{
public:
    SeqList(int capcity);
    ~SeqList();
    int getLength();

    int getCapacity();

    int insert(T &t, int pos);

    int get(int pos,T& t);

    int Delete(int pos, T& t);

private:
    int length;
    int capacity;
    T  *pArray;
};

  • 实现文件
#include "SeqList.h"

template 
SeqList::SeqList(int capcity)
{
    pArray = new T[capcity];
    this->capacity = capcity;
    this->length = 0;
}

template 
SeqList::~SeqList()
{
    delete[]pArray;
    pArray = NULL;
    length = 0;
    capacity = 0;
}

template 
int SeqList::getLength()
{
    return length;
}

template 
int SeqList::getCapacity()
{
    return capacity;
}

template 
int SeqList::insert(T &t, int pos)
{
    int  i = 0;
    if ( pos < 0)
    {
        return -1;
    }

    for (i = length; i> pos; i--)
    {
        pArray[i] = pArray[i - 1];
    }

    pArray[i] = t;

    length++;

    return 0;
}

template 
int SeqList::get(int pos, T& t)
{
    if ( pos < 0)
    {
        return -1;
    }

    t = pArray[pos];

    return 0;
}

template 
int SeqList::Delete(int pos, T& t)
{
    int  i = 0;

    if ( pos < 0)
    {
        return -1;
    }

    t = pArray[pos];

    for (i = pos + 1; i <length;i++)
    {
        pArray[i - 1] = pArray[i];
    }
    length--;

    return 0;
}
  • 测试文件
  • #include 
    #include "SeqList.cpp"
    using namespace std;
    
    typedef struct _teacher
    {
        char name[64];
        int age;
    }Teacher;
    
    void main_play(void)
    {
    
        Teacher t1, t2, t3,tmp;
        t1.age = 31;
        t2.age = 32;
        t3.age = 33;
    
        SeqList list(10);
    
        list.insert(t1, 0);
        list.insert(t2, 0);
        list.insert(t3, 0);
    
        for (int i = 0; i < list.getLength();i++)
        {
            list.get(i, tmp);
            cout << tmp.age << " ";
        }
    
        while (list.getLength()>0)
        {
            list.Delete(0,tmp);
            cout << tmp.age << " ";
        }
    
        return;
    }
    
    int main(void)
    {
    
        main_play();
    
        cout << "Hello!" << endl;
        system("pause");
        return 0;
    }


你可能感兴趣的:(数据结构)