C++データ構造とアルゴリズム(一)線形表の順序表
12158 ワード
Seqlist.h:
test.cpp
const int DefaultSize = 100;
template <class T>
class SeqList
{
public:
SeqList(int sz = DefaultSize)
:m_nmaxsize(sz),m_ncurrentsize(-1)
{//
if(sz > 0)
{
m_element = new T[m_nmaxsize];
}
}
~SeqList()
{
delete[] m_element;
}
int Length() const;////
int Find(T x) const;// x
int IsElement(T x) const; // x
int Insert(T x,int i);// x
int Delete(T x);// x
int IsEmpty() const;//
int IsFull() const;//
T GetElement(int i);// i
void Print();
private:
T* m_element;
const int m_nmaxsize;
int m_ncurrentsize;
};
template<class T>
int SeqList<T>::Length() const
{
return m_ncurrentsize + 1;
}
template<class T>
int SeqList<T>::Find(T x) const
{
for(int i = 0 ;i < m_ncurrentsize; i++)
{
if(m_element[i] == x)
return i;
}
cout << " " << endl;
return -1;
}
template<class T>
int SeqList<T>::IsElement(T x) const
{
if(Find(x) == -1)
return 0;
else
return 1;
}
template<class T>
int SeqList<T>::Insert(T x, int i)
{
if(i < 0 || i > m_ncurrentsize + 1 || m_ncurrentsize == m_nmaxsize - 1)
{
cout << " " << endl;
return 0;
}
m_ncurrentsize ++;
for(int j = m_ncurrentsize; j >i; j --)
{
m_element[j] = m_element[j-1];
}
m_element[i] = x;
return 1;
}
template<class T>
int SeqList<T>::Delete(T x)
{
int nsize = m_ncurrentsize;
for(int i = 0; i< m_ncurrentsize; i++)
{
if(m_element[i] == x)
{
for(int j = i; j < m_ncurrentsize; j ++)
{
m_element[j] = m_element[j+1];
}
m_ncurrentsize --;
continue;
}
}
if(nsize = m_ncurrentsize)
{
cout << " " << endl;
return 0;
}
return 1;
}
template<class T>
int SeqList<T>::IsFull() const
{
return m_ncurrentsize == m_nmaxsize -1;
}
template<class T>
T SeqList<T>::GetElement(int i)
{
if(i < 0 || i > m_nmaxsize)
{
cout << " " << endl;
return 0;
}
return m_element[i];
}
template<class T>
void SeqList<T>::Print()
{
for(int i = 0 ;i <= m_ncurrentsize;i ++)
{
cout << i + 1 << ":\t" << m_element[i] << endl;
}
}
test.cpp
// test.cpp : 。
//
#include "stdafx.h"
#include "Seqlist.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
SeqList<int> list;
int a[15] = {4,8,8,2,9,1,7,6,4,3,2,9,11,7,9};
for(int i = 0; i< 15 ;i ++)
{
list.Insert(a[i],i);
}
list.Print();
cin.get();
return 0;
}