One way circular list exercise Joseph Ring problem

Keywords: Programming

Problem description

Josephus ring (Josephus problem) is a mathematical application problem: known n individuals (represented by numbers 1, 2, 3...n respectively) sit around a round table clockwise, each holding a password (positive integer). At the beginning, select an integer as the upper limit value m of the report, report clockwise from the first person, stop reporting when reporting to m, the person reporting m will be listed, his password will be the new m value, and the next person reporting to m in the clockwise direction will be listed again from 1, and the person reporting to m will be listed again; repeat this rule until all the people around the round table are listed.

Input format

Number n in the first line indicates the number of people in the round table;
The second line is n integers, indicating the password held by the guests in the round table:
The third line is an integer, representing the initial m value;

Output format

The order in which people leave the table

sample input

 7
3 1 7 2 4 8 4
20
 

sample output

6       1       4       7       2       3       5 

Solving problems

This problem only needs to pay attention to the head node of the linked list when it is looped.

code implementation

 

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
	int data;
	int index;
	struct Node *next;
} Node, *LinkList;

void initLink(LinkList *link);
void create(LinkList link, int size);
int main(int argc, char *argv[]) {
	int m = 0, n = 0, count = 1, sum = 0;
	// Pointer p points to the position when the number is reported, and pointer q points to the previous bit when the number is reported
	Node *p, *q;
	scanf("%d", &n);
	LinkList link;
	initLink(&link);
	create(link, n);
	scanf("%d", &m);
	p = link->next;
	while (sum != n) {
		if (count == m) {
			printf("%d\t", p->index);
			m = p->data;
			q->next = p->next;
			free(p);
			p = q->next;
			count = 0;
			sum++;
		} else {
			q = p;
			p = p->next;
		}
		// When the pointer p points to the head pointer of the linked list, the pointer moves backward one bit
		if (p->index == -1) {
			q = p;
			p = p->next;
		}
		count++;
	}
	return 0;
}

void initLink(LinkList *link) {
	*link = (LinkList)malloc(sizeof(Node));
	(*link)->next = NULL;
	(*link)->index = -1;
}

void create(LinkList link, int size) {
	int i;
	Node *node, *q;
	q = link;
	for (i = 0; i < size; i++) {
		node = (Node *)malloc(sizeof(Node));
		scanf("%d", &node->data);
		node->index = i + 1;
		link->next = node;
		link = node;
	}
	link->next = q;
}

Posted by gonsman on Sat, 30 Nov 2019 16:20:39 -0800