关闭

约瑟夫环-顺序表-C++

149人阅读 评论(0) 收藏 举报
分类:
#include <iostream>
using namespace std;

template<class T>
class SeqList
{
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);
	friend ostream &operator<<<T>(ostream &out,SeqList<T> &list);
	void insert(int i,T x);
	void insert(T x);
	bool remove(int i,T &old);
	void clear();

private:
	T *element;
	int size;
	int len;
};

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;
		this->len=n;

		for(int i=0;i <n;i ++)
		{
			this->element[i]=value[i];
		}
	}
}

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];
	}
	return 'F';
}

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>
ostream &operator<<(ostream &out,SeqList<T> &list)
{
	out<<"(";
	if (list.len>0)
	{
		out<<list.element[0];
		for (int i=1;i<list.len;i++)
		{
			out<<","<<list.element[i];
		}
	}
	out<<")\n";
	return out;
}

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[j];
	}
	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"
#include <iostream>
using namespace std;

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);
	system("pause");
	return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2056次
    • 积分:165
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:1篇
    • 译文:2篇
    • 评论:0条