马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 刹那芳华 于 2013-9-11 15:41 编辑 #include <iostream>
using namespace std;
template <class T>
class SeqList;
template <class T>
class SeqList
{
public:
T *element;
int size;
int len;
public:
SeqList(int size = 64);
SeqList(T value[],int n);
~SeqList();
bool isEmpty();
int length();
T get(int i);
bool set(int i,T x);
/* void display(SeqList<T> &list)
{
for(int i=0;i<list.len;i++)
{
cout<<element[i]<<",";
}
}*/
friend ostream& operator << (ostream&,const SeqList<T>&);
void insert(int i,T x);
void insert(T x);
bool remove(int i,T& old);
void clear();
};
template <class T>
SeqList<T>::SeqList(int size)
{
this->size = size<64?64:size;
this->element = new T[this->size];
this->len = 0;
}
template <class T>
SeqList<T>::SeqList(T value[],int n)
{
if(n>0)
{
this->element = new T[2*n];
this->size = 2*n;
for(int i=0;i<n;i++)
this->element[i] = value[i];
this->len = n;
}
};
template <class T>
ostream & operator<<(ostream & out,SeqList<T> &list)
{
out<<"(";
if(list.len>0)
{
out<<list.element[0];
for(int i = i;i<list.len;i++)
out<<","<<list.element[i];
}
out<<")\n";
return out;
}
template <class T>
SeqList<T>::~SeqList()
{
delete []this->element;
}
template <class T>
bool SeqList<T>::isEmpty()
{
return len == 0;
}
template <class T>
int SeqList<T>::length()
{
return len;
}
template <class T>
T SeqList<T>::get(int i)
{
if(i>=0&&i<len)
return element[i];
throw "参数i指定的元素序号无效";
}
template <class T>
bool SeqList<T>::set(int i,T x)
{
if(i>=0&&i<len)
{
element[i] = x;
return true;
}
return false;
};
template <class T>
void SeqList<T>::insert(int i, T x)
{
if(len==size)
{
T *temp = element;
element = new T[size*2];
for(int i=0;i<size;i++)
element[i]=temp[i];
//size* = 2;
}
if(i<0) i = 0;
if(i>len) i = len;
for(int j = len-1;j>=i;j--)
element[j+1]=element[i];
element[i] = x;
len++;
}
template <class T>
void SeqList<T>::insert(T x)
{
insert(len,x);
}
template <class T>
bool SeqList<T>::remove(int i,T &old)
{
if(len>0&&i>=0&&i<len)
{
old = element[i];
for(int j = i;j<len;j++)
element[j] = element[j+1];
len--;
return true;
}
return false;
}
template <class T>
void SeqList<T>::clear()
{
len = 0;
}
上面是顺序表类
下面是调用这个类解决问题,比如约瑟夫环问题,这只是举个例子,还可以有很多用法#include "SeqList.h"
void josephus(int number,int start,int distance)
{
SeqList<char> jose(number);
int i=0;
for(i = 0;i<number;i++)
{
jose.insert('A'+i);
}
cout<<"约瑟夫环("<<number <<","<<start<<","<<distance<<"),"<<jose;
i = start;
while(jose.length()>1)
{
i = (i+distance - 1)%jose.length();
char old;
if(jose.remove(i,old))
cout<<"删除"<<old<<",";
cout<<jose;
}
cout<<"被赦免的是"<<jose.get(0)<<"\n";
}
int main()
{
josephus(5,0,2);
return 0;
}
|