002 -- Circle LinkList_Josephus Story

Posted ReedyLi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了002 -- Circle LinkList_Josephus Story相关的知识,希望对你有一定的参考价值。

Circle List puzzle

Josephus Story:

there is 41 people , 39 of them have the agreement that: all these 41 people stand as a circle, and one of them count from 1, and the one count to 3, suicide ! and the people next to him count from 1 again, untill all 41 people are dead. But Josephus and his friend don‘t want to die, so they have their location arranged, and become the last 2 person for counting. 

 

// give a number m, n people as a circle and start say a number with 1, the one with number m to say, get out of the circle 

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

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

node *create(int n)
{
    node *p = NULL, *head;
    head = (node*)malloc(sizeof(node));
    p = head;
    node *s;
    int i = 1;
    
    if(0!n)
    {
        while(i<=n)
        {
            s = (node*)malloc(sizeof(node));
            s->data=i++; //initiate the circle list, the first node is 1; the secode node is 2
            p->next = s;
            p=s;
        }
        s->next = head->next;
        
    }
    
    free(head);
    return s->next;
}

int main()
{
    int n = 41; //total 41 people_initiate a list with 41 nodes 
    int m = 3; //who count to 3, out of circle _delete the node 
    int i;
    node *p = create(n);
    node *temp;
    
    m = n%m; //m=2
    
    while(p!=p->next) //if p = p->next, means only 1 node left in the list 
    {
        for (i=1;i<m-1;i++)
        {
            p=p->next; //now p come to the node before the deleting node, only run 1 time
        }
        
        printf("%d", p->next->data); //print the value of the node who going to be deleted
        
        temp = p->next;
        p->next = temp->next;
        free(temp);
        
        p=p->next; // now p point to the node who will start count with 1
        
    }
    
    printf("%d\n",p->data);  //print the last node of the list 
    
    return 0;
}

 

以上是关于002 -- Circle LinkList_Josephus Story的主要内容,如果未能解决你的问题,请参考以下文章

002 -- Circle LinkList 3 -- Puzzels_Magic Poker and Latin

初识OpenCV-Python - 002: Drawing functions

turtle 库练习

turtle库基础练习

绘制玫瑰

SVG <circle> 填充覆盖前一个圆圈