利用循环链表(单链)实现Josephus环(某公司校园招聘笔试试题)

#include<iostream>
using namespace std;

typedef struct node
{
	int data;
	struct node *next;
}Node;

Node *createRing(int n)
{
	Node *p = new Node[n]; //批量生成结点
	int i;
	for(i = 0; i < n; i++)
	{
		p[i].data = i + 1;
		p[i].next = &p[(i + 1) % n];
	}
	
	return p;
}

Node *move(Node *p, int gap) //以p为第一个,定位到第gap个
{
	int i;
	for(i = 0; i < gap - 1; i++)
		p = p->next;

	return p;
}

int main()
{
	int total, start, gap;
	cin >> total >> start >> gap;

	Node *p = createRing(total);
	Node *pNow = move(p, start); //初始位置

	Node *p1, *p2;
	int i;
	for(i = 0; i < total -1; i++) // n-1次脱链
	{
		p1 = move(pNow, gap - 1);
		p2 = p1->next;

		pNow = p2->next;
		p1->next = p2->next;//脱链
		
		cout << p2->data << " ";
	}
	cout << pNow->data << endl;

	delete [] p;

	return 0;
}


输入:10 3 4

结果为:

10 3 4
6 10 4 9 5 2 1 3 8 7

你可能感兴趣的:(利用循环链表(单链)实现Josephus环(某公司校园招聘笔试试题))