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

C++实现数据结构一 顺序表

2013-04-09 19:16 453 查看
const int Default= 100;

template<typename Type> class SeqList
{
private:
Type *m_elements;
const int m_maxsize;
int m_currentsize;

public:
//构造函数
SeqList(int size = Default): m_maxsize(size), m_currentsize(0)
{
if(size > 0)
m_elements = new Type[m_maxsize];
}

//析构函数
~SeqList()
{
delete [] m_elements;
}

int Length() const
{
return m_currentsize;
}
int Find(Type x) const;
int IsElement(Type x) const;
int Insert(Type x, int i);
int Remove(Type x);
int IsEmpty()
{
return m_currentsize ==0 ;
}
int IsFull()
{
return m_currentsize == m_maxsize;
}
Type Get( int i );

void Print();
};

/*
函数功能:查找指定元素在顺序表的位置
函数参数:Type 类型的 x
函数返回值:返回该元素的位置,未找到则返回 0
*/
template<typename Type>
int SeqList<Type>::Find(Type x) const
{
int i;
for(i=0; i<m_currentsize; i++)
{
if(x == m_elements[i])
{
cout<<"find the element: "<<x<<endl;
return i+1;
break;
}
}
if(i == m_currentsize)
{
cout<<"cannot find the element: "<<x<<endl;
return 0;
}
}

/*
函数功能:判断指定元素是否在顺序表中
函数参数:Type 类型的x;
函数返回值:在顺序表中返回1,否则返回0;
*/
template<typename Type>
int SeqList<Type>::IsElement(Type x) const
{
int i =Find(x);
if( i == 0)
{
cout<<x<<" is not in the list"<<endl;
return 0;
}
else
return 1;
}

/*
函数功能:在顺序表指定的位置插入指定的元素
函数参数:Type类型的x, int类型的i
函数返回值:插入成功返回1, 否则返回0;
*/
template<typename Type>
int SeqList<Type>::Insert(Type x, int i)
{
if(i<1 || i>m_currentsize+1 || m_currentsize == m_maxsize)
{
cout<<"cannot insert the element "<<endl;
return 0;
}

m_currentsize++;
for(int j = m_currentsize-1; j>i-1;j--)
m_elements[j]= m_elements[j-1];
m_elements[i-1]= x;
return 1;
}

/*
函数功能:移除顺序表中的指定元素
函数参数:Type类型的x
函数返回值:移除成功返回1,否则返回0
*/
template<typename Type>
int SeqList<Type>::Remove(Type x)
{
int i = Find(x);
if(i == 0)
{
cout<<"can not remove the element"<<endl;
return 0;
}

for(int j= i-1; j<m_currentsize-1; j++)
m_elements[j] = m_elements[j+1];
m_currentsize--;
return 1;
}

/*
函数功能:获取顺序表中指定位置的元素的值;
函数参数:int 类型的变量i
函数返回值:返回i位置处的元素之,失败则返回0;
*/
template<typename Type>
Type SeqList<Type>::Get(int i)
{
if(i<1 || i> m_currentsize)
{
cout<<"cannot get the element"<<endl;
return 0;
}

return m_elements[i-1];
}

/*
函数功能:输出顺序表的所有元素
函数参数:无
函数返回值:无
*/
template<typename Type>
void SeqList<Type>::Print()
{
for(int i=0; i<m_currentsize; i++)
cout<<m_elements[i]<<"\t";
cout<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: