Joseph Ring (Loop List Implementation)

One description of Joseph's problem is: n people numbered 1, 2, 3, ..., n sit in a circle in a clockwise direction. Each person holds a password (positive integer). At the beginning, any positive integer is selected as the upper limit of the number m. Starting from the first person, the number is reported in clockwise direction starting from 1. When m is reported, the number is stopped, the person is dequeued, and his password is used as the new one. m value, start counting again from the next person in the clockwise direction, and so on until everyone is out of the queue. Try to design a program to find the dequeuing order.

    Experimental requirements

The one-way circular linked list storage structure of the headless node is used to simulate this process, and each person's number is printed out in the order in which they are listed.

Test Data:

    The initial value of m is 20; n=7, the passwords of 7 people are: 3, 1, 7, 2, 4, 8, 4. First, the value of m is 8 (the correct dequeuing order should be 6, 1, 4 ,7,2,3,5)

 Experimental tips:

    After the program is run, the user is first required to specify the initial upper limit of the number, and then reads each person's password. You can set n<=30. There is no "head node" in the circular linked list used in this question. Please pay attention to the empty list and The bounds of a non-empty table.

#include<iostream>//用链表实现约瑟夫环问题 (循环链表)
using namespace std;
typedef struct node  
{
	int num;
	int pwd;
	struct node* next;
}Node ,*list;
list Createlist(int n)//创建循环列表
{
	list head = NULL,rear=NULL, temp = NULL;
	head = rear;
	for (int i = 1; i <= n; i++)
	{
		temp = new node;
		temp->num = i;
		cin >> temp->pwd;
		if (head == NULL)//若为空则赋给头指针
		{
			head = temp;
		}
		else
		{
			rear->next = temp;//接在尾指针后
		}
		rear = temp;
	}
	rear->next = head;//尾指针指向头指针
	return head;
}
//void Printlist(list l)//打印输出
//{
	//list p = l;
	//for (int i = 0; i < 14; i++)
	//{
		//cout << p->num << p->pwd << " ";
		//p = p->next ;
	//}
	//cout << endl;
//}
void Getlist(list l,int n,int m)//约瑟夫环
{
	list p = l, q = NULL;
	while (p->next != p)//循环直到只剩一个 头尾相指
	{
		for (int i = 1; i < m; i++)
		{
			q = p;//保留离开点的上一个节点
			p = p->next;
		}
		cout << p->num<<" ";
		m = p->pwd;
		q->next = p->next;//剔除该点
		p = p->next;//从下一节点重新计数
	}
	cout << p->num;
}
int main()
{
	list l;
	int n, m;
	cin >> n >> m;
	l = Createlist(n);
	//Printlist(l);
	Getlist(l, n, m);
}

おすすめ

転載: blog.csdn.net/qq_74156152/article/details/132819401