码迷,mamicode.com
首页 > 其他好文 > 详细

002 -- Circle LinkList_Josephus Story

时间:2017-09-15 02:12:50      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:ber   null   i++   eof   for   number   josephus   and   hat   

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

标签:ber   null   i++   eof   for   number   josephus   and   hat   

原文地址:http://www.cnblogs.com/Shareishappy/p/7523647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!