这篇文章给大家分享的是有关C++中数据结构线性表之数组实现的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
C++ 数据结构线性表-数组实现
/* Author : Moyiii
* 线性表的数组实现,仅作学习之用,当然如果
* 你想拿去用,随你好啦。
*/
#include<iostream>
using namespace std;
//顺序表
class SeqList
{
public:
//构造函数,接受一个默认的列表大小
SeqList(int size = MAX_LIST_SIZE);
//析构函数,释放elems占用的内存空间
~SeqList();
//清空表
void clear();
//判断表是否为空
bool isEmpty();
//获得表的当前元素个数
int getLength();
//在第pos个元素位置之前插入一个新元素
bool insertElem(int pos, int elem);
//删除第pos个元素
bool deleteElem(int pos);
//打印表中元素
void print();
int *elems;//表元素,
private:
static const int MAX_LIST_SIZE;
int m_length;//表的元素个数
int m_size;//表的当前最大长度
};
SeqList :: SeqList(int size)
{
//size不可以小于零,也不可以超过系统规定最大长度
//否则做截断处理
if(size > MAX_LIST_SIZE)
{
m_size = MAX_LIST_SIZE;
}
else if(size < 0)
{
m_size = 0;
}
else
{
m_size = size;
}
elems = new int[m_size];
m_length = 0;
if(!elems)
{
cout << "Space allocate failed!" << endl;
}
}
SeqList :: ~SeqList()
{
delete []elems;
}
void SeqList :: clear()
{
m_length = 0;
}
bool SeqList :: isEmpty()
{
if(m_length == 0)
{
return true;
}
else
{
return false;
}
}
int SeqList :: getLength()
{
return m_length;
}
bool SeqList :: insertElem(int pos, int elem)
{
if(m_length == m_size)
{
cout << "List is Full" << endl;
return false;
}
if(pos < 1 || pos > m_length + 1)
{
cout << "Over Bound!" << endl;
return false;
}
//插入位置之后元素后移
for(int i = m_length; i >= pos - 1; --i)
{
elems[i+1] = elems[i];
}
elems[pos-1] = elem;
m_length++;
return true;
}
bool SeqList :: deleteElem(int pos)
{
if(pos < 1 || pos > m_length)
{
return false;
}
for(int i = pos - 1; i <= m_length - 1; ++i)
{
elems[i] = elems[i+1];
}
m_length--;
return false;
}
void SeqList :: print()
{
for(int i = 0; i < m_length; ++i)
{
cout << elems[i] << " ";
}
cout << endl;
}
//初始化
const int SeqList :: MAX_LIST_SIZE = 100;
int main()
{
SeqList myList;
for(int i = 1; i <= 10; ++i)
{
myList.insertElem(1,i);
}
myList.print();
cout << "Length= " << myList.getLength() <<endl;
myList.deleteElem(5);
myList.print();
cout << "Length= " << myList.getLength() <<endl;
myList.clear();
cout << myList.isEmpty() << endl;
return 0;
}
感谢各位的阅读!关于“C++中数据结构线性表之数组实现的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。