您的位置:首页 > 理论基础 > 数据结构算法

数据结构之顺序链表

2016-04-24 19:36 525 查看
       顺序表存储位置是相邻连续的,可以随即访问的一种数据结构,一个顺序表在使用前必须指定起长度,一旦分配内存,则在使用中不可以动态的更改。他的优点是访问数据是比较方便,可以随即的访问表中的任何一个数据。

       顺序表和数组类似,只不过多了几个自己编写的插入删除之类的接口。

#include "stdafx.h"

#include <iostream>

using namespace std;

template <class T>

class SeqList

{

public:
SeqList(int initialval1,int initialval2,T* initialval3=NULL):pElem(initialval3),nLength(initialval1),maxLength(initialval2)
{
if (0 == initialval2)
{
pElem = NULL;
}
else
 pElem = new T[initialval2]();

}
SeqList(const SeqList& rh)
{
pElem = rh.pElem;
nLength = rh.nLength;
maxLength = rh.maxLength;
}
SeqList operator=(const SeqList& rh);

void Seq_Insert(const T& rh, int i);
void Seq_Delete(int i);

public:
T* pElem;
int nLength;
int maxLength;

};

template <class T>

SeqList<T> SeqList<T>::operator=(const SeqList& rh)

{
SeqList<T> seq;
seq.nLength = rh.nLength;
seq.maxLength = rh.maxLength;
seq.pElem = new T[maxLength]();
memcpy(seq.pElem, rh.pElem, maxLenght * sizeof(T));

return seq;

}

template <class T>

void SeqList<T>::Seq_Insert(const T& rh, int i)

{
if (i<=nLength)
{
pElem[i-1] = rh;
nLength++;
for (int j = i ; j < nLength + 1 && j < maxLength; j++)
{
pElem[j] = pElem[1 + i++];
}
}
else
{
cout << "Insert Error!" << endl;
}

}

template <class T>

void SeqList<T>::Seq_Delete(int i)

{
if (i<=nLength)
{
for (int j=i-1;i<nLength-1;)
{
pElem[j] = pElem[i++];
}
}
else
{
cout << "Delete Error!" << endl;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: