C language code implementation of Josephus ring problem algorithm

Keywords: C

One description of Joseph's problem is: n people numbered 1, 2,... N sit in a clockwise circle, each holding a password (positive integer). At the beginning, select a positive integer as the upper limit value m of the number reported. The number is reported from the first person in a clockwise direction starting from 1, and stops when the number is reported to M. The person who reported m listed his password as a new m value, starting from the next person in the clockwise direction and reporting again from 1, so on, until all the people listed. Try to design a program to find out the sequence.

Basic Requirements

This process is simulated by using the storage structure of unidirectional circular list, and the number of each person is printed out according to the sequence of listing.

test data

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

Implementation hint

After the program runs, the user is required to specify the upper limit value of the initial number of calls, and then read each person's password. Set n < = 30. "Header node" is not needed in the circular linked list used in this problem. Please pay attention to the boundary between empty and non empty tables.

Algorithm code:
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
#define N 7
struct Student
{
    int number;
    int password;
    struct Student *next;
};


struct Student *creat(void)
{
    struct Student *head;
    struct Student *p1,*p2;
    int n=0;
    p1=p2=(struct Student *)malloc(LEN);
    scanf("%d,%d",&p1->number,&p1->password);
    head=NULL;
    while(p1->number!=0)
    {
        n=n+1;
        if(n==1)head=p1;
        else p2->next=p1;
        p2=p1;
        p1=(struct Student *)malloc(LEN);
        scanf("%d,%d",&p1->number,&p1->password);
    }
    p2->next=head;
    return(head);
}

void Joseph(struct Student *head,int count)
{
    int m;
    struct Student *p;
    p=head;
    
        for(m=1;m<count-1;m++)
            p=p->next;
        printf("%d,%d\n",(p->next)->number,(p->next)->password);
        count=p->next->password;
        p->next=p->next->next;
    do{
        for(m=1;m<count;m++)
            p=p->next;
        printf("%d,%d\n",(p->next)->number,(p->next)->password);
        count=p->next->password;
        p->next=p->next->next;
    
    }while(p!=p->next);

    printf("%d,%d\n",p->number,p->password);
}

void main()
{
    struct Student *Head;
    int num;
    printf("Please enter your serial number and password:\n");
    Head=creat();
    printf("Please specify the upper limit value of the initial call:\n");
    scanf("%d",&num);
    Joseph(Head,num);
}
Operation result:

Posted by 8mycsh on Fri, 13 Dec 2019 08:40:32 -0800