刹那芳华 发表于 2013-9-11 15:39:13

给大家发福利,循序表“类”及应用

本帖最后由 刹那芳华 于 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<<",";
}
}*/
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->len = 0;
}
template <class T>
SeqList<T>::SeqList(T value[],int n)
{
if(n>0)
{
this->element = new T;
this->size = 2*n;
for(int i=0;i<n;i++)
this->element = value;
this->len = n;
}
};
template <class T>
ostream & operator<<(ostream & out,SeqList<T> &list)
{
out<<"(";
if(list.len>0)
{
out<<list.element;
for(int i = i;i<list.len;i++)
out<<","<<list.element;
}
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;
throw "参数i指定的元素序号无效";
}
template <class T>
bool SeqList<T>::set(int i,T x)
{
if(i>=0&&i<len)
{
element = 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;
for(int i=0;i<size;i++)
element=temp;
//size* = 2;
}
if(i<0) i = 0;
if(i>len) i = len;
for(int j = len-1;j>=i;j--)
element=element;
element = 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;
for(int j = i;j<len;j++)
element = element;
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;
}

刹那芳华 发表于 2013-9-11 15:41:49

2楼还是我的,有问题大家可以互相交流

復襍 发表于 2013-9-15 11:44:45

路过看一看有什么好东西收藏一下,强烈支持楼主ing……37733

hesongnian123 发表于 2013-9-15 20:17:35

学习了学习了

轻云流风 发表于 2013-9-22 09:03:53

顶起,代码真整洁,如在加一点注释就更完美了

icecool 发表于 2013-9-23 14:54:57

学习了 ~~~~
页: [1]
查看完整版本: 给大家发福利,循序表“类”及应用