首页 > 代码库 > C++:顺序表类实现约瑟夫问题_密码不同

C++:顺序表类实现约瑟夫问题_密码不同

//.h

#pragma once
#include <iostream>
using namespace std;
#define MAXSIZE 100

template <class T>
class SeqList
{
T data[MAXSIZE];
int length;
public:
SeqList();
SeqList(T a[],int n);
~SeqList();
void Josephus2(int p[], int m0);
void PrintList();
};


template <class T>
SeqList<T>::SeqList()
{
length = 0;
}

template<class T>
SeqList<T>::SeqList(T a[], int n)
{
length = n;
for (int i = 0; i < length; i++)
data[i] = a[i];
}

template <class T>
SeqList<T>::~SeqList()
{
}

template<class T>
void SeqList<T>::Josephus2(int p[], int m0)
{
int k = 1;
int m = m0;
cout << " 出圈顺序为:" << endl;
while (length != 0)
{
k--;
int i = (k + m - 1) % length;
cout << data[i] << " ";
m = p[i];
for (int j = i; j < length - 1; j++)
{
data[j] = data[j + 1];
p[j] = p[j + 1];
}
length--;
k = i + 1;
}
cout << endl;
}

template<class T>
void SeqList<T>::PrintList()
{
for (int i = 0; i < length; i++)
cout << data[i] << " ";
cout << endl;
}

 

// 约瑟夫问题 密码不同.cpp : 定义控制台应用程序的入口点。
//主函数

#include "stdafx.h"
#include "SeqList.h"
#include <iostream>
using namespace std;

int main()
{
int a[6] = { 1,2,3,4,5,6 };
int b[6] = { 1,2,3,4,5,6 };

SeqList<int> s(a,6);
s.PrintList();
s.Josephus2(b,3);

system("PAUSE");
return 0;
}

 

C++:顺序表类实现约瑟夫问题_密码不同