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

数据结构---线性顺序表操作(c++)

2015-09-08 20:53 381 查看
1、线性顺序表:必要属性 元素类型指针, 元素容量, 元素的实际长度

2、操作方法:

//创建
//销毁
//清空
//插入
//删除
//获取容量
//获取长度
//获取某一元素所在的位置
//获取指定位置的元素

#include "stdio.h"
#include <windows.h>
#include <iostream>
#include <string.h>

template<class Type>
class COrderList
{
public:
COrderList():m_pBuf(NULL), m_nMax(0), m_nLen(0)
{

}
~COrderList()
{
ListDestory();
}

public:
//创建
bool ListCreate(_In_ int nMaxLen)
{
if (nMaxLen>0)
{
//非空设置空
if (m_pBuf)
{
delete []  m_pBuf;
m_pBuf = nullptr;

}

//创建并初始化
m_pBuf = new Type[nMaxLen];
memset(m_pBuf, 0, sizeof(Type)*nMaxLen);
m_nMax = nMaxLen;
return true;
}

return false;
}

//销毁
void ListDestory()
{
if (m_pBuf)
{
delete [] m_pBuf;
m_pBuf = nullptr;
m_nMax = 0;
m_nLen = 0;
}
}

//清空数据 但是最大的容量是存在
void ListEmpty()
{
if (m_nLen > 0)
{
m_nLen = 0;
}
}

//插入
bool ListInsert(_In_ int idx, _In_ Type type)
{

//判断是否越界
if (idx <0 || idx>m_nLen)
{
return false;
}

//如果为空 则开辟空间
if (!m_pBuf)
{
ListCreate(8);
}

//当m_len = m_max
if (m_nLen == m_nMax)
{
Type * t = new Type[2*m_nMax];
memset(t, 0, sizeof(Type)*2*m_nMax);

//将原来的拷贝进来
for (int i=0; i<m_nLen; i++)
{
t[i] = m_pBuf[i];
}
delete [] m_pBuf;
m_pBuf = nullptr;
m_pBuf = t;
m_nMax = 2*m_nMax;
}

//进行添加数据  将所有的元素后移  因为是增加我们从后面开始移动
for (int i=m_nLen; i>idx; i--)
{
//将前面的一个元素 赋值给后一个元素
m_pBuf[i] = m_pBuf[i-1];
}
m_pBuf[idx] = type;

//长度自增
m_nLen++;

return true;

}

//删除
bool ListDel(_In_ int idx, _Out_ Type tpye)
{
//判断参数
if (idx< 0 || idx>=m_nLen)
{
return false;
}

//判断属性
if (!m_pBuf)
{
return false;
}

//将要删除的元素进行保存
tpye = m_pBuf[idx];

//进行删除  将所有的元素前移  从前面开始
for (int i=idx; i<m_nLen; i++)
{
m_pBuf[i] =m_pBuf[i+1];
}

//长度自减
m_nLen--;
}

//获取容量
int ListCount()
{
return m_nMax;
}

//获取长度
int ListLen()
{
return m_nLen;
}

//获取某一元素所在的位置
int ListIsExist(_In_ Type type)
{
if (m_pBuf)
{
for (int i=0; i<m_nLen; i++)
{
if (m_pBuf[i] == type)
{
return i;
}
}
}
return -1;
}

//获取指定位置的元素
void ListEleByIdx(_In_ int idx, _Out_ Type &type)
{
if (idx>=0 && idx < m_nLen)
{
type = m_pBuf[idx];
}
}

//打印所有的元素
void ListPrint()
{
if (m_pBuf)
{
for (int i=0; i<m_nLen; i++)
{
std::cout<< m_pBuf[i]<<std::endl;
}
std::cout<<std::endl;
}
}
private:
Type * m_pBuf;   //封装数据的指针
int m_nLen;	  //实际的长度
int m_nMax;      //最大长度
};

int main()
{
//创建
COrderList<int>  co;
co.ListCreate(2);

//插入
co.ListInsert(0, 11);
co.ListInsert(0, 22);
co.ListInsert(0, 33);

//打印输出
co.ListPrint();

printf("总的数量: %d \n", co.ListCount());
printf("长度数量: %d \n", co.ListLen());

//获取指定位置的元素
int temp = 0;

co. ListEleByIdx(2, temp);
printf("temp: %d \n", temp);

//获取元素的位置
printf("获取元素的位置: %d \n", co.ListIsExist(11));

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