循环链表解决约瑟夫环问题

#include<iostream>
using namespace std;
typedef struct node* list;
struct node
{
	int data;
	node* next;
};
list insert(list l,int x)
{
	node* newNode = new node;
	newNode->data = x;
	if (l==NULL)
	{
		newNode->next = newNode;
		l = newNode;
	}
	else
	{
		list last = l;
		while (last->next != l)
			last = last->next;
		newNode->next = last->next;
		last->next = newNode;
	}
	return l;
}
void james(list l, int n, int m)
{
	int i, j;
	list pre = new node;
	list p = l;
	for (i = 0; i < n - 1; i++)
	{
		for (j = 1; j < m; j++)
		{
			pre = p;
			p = p->next;
		}
		cout << "出列的人是" << p->data << endl;
		pre->next = p->next; 
		delete p;
		p = pre->next;
	}
}
int main()
{
	list l = NULL;
	list last = l;
	int i, n, m;
	cout << "输出游戏者人数和报数间隔";
	cin >> n >> m;
	for (i = 1; i <= n; i++)
	  l=insert(l,i);
	james(l, n, m);
}

posted @ 2020-09-13 14:24  _Hsiung  阅读(67)  评论(0编辑  收藏  举报