使用链表实现Josephus环问题

分析:先创建一个有total个结点的链表,然后头尾相连,构成一个环形链表。从第一个结点开始数到第m个结点,从链表中删除对应结点,表示小孩出圈。然后再从被删除结点的下一个结点重新开始计数,直到链表中剩下最后一个结点。

#include  < stdlib.h >
#include 
< stdio.h >
#define  LEN sizeof(struct child)
struct  child 
{
    
int  num;
    
struct  child  * next;
};

void  main()
{
    
struct  child  * create( int  num);
    
int  count( struct  child  * head, int  total, int  m);
    
struct  child  * head;
    
int  total,m,n;
    printf(
" please input total and start: " );
    
do  
    {
        scanf(
" %d%d " , & total, & m);
    } 
while (total < 2 || m < 2 || m > total);
    head
= create(total);
    n
= count(head,total,m);
    printf(
" \nThe left child is %d\n " ,n);
}

struct  child  * create( int  num)
{
    
struct  child  * p1, * p2, * head;
    
int  i;
    p1
= ( struct  child  * )malloc(LEN);
    p1
-> num = 1 ;
    head
= p1;
    
for  (i = 2 ;i <= num;i ++ )
    {
        p2
= ( struct  child  * )malloc(LEN);
        p2
-> num = i;
        p1
-> next = p2;
        p1
= p2;
    }
    p1
-> next = head;                     // 头尾相连
     return  head;
}

int  count( struct  child  * head, int  total, int  m)
{
    
struct  child  * p = head, * old;
    
int  i,j;
    
for  (i = 1 ;i < total;i ++ )             // 循环次数
    {
        
for  (j = 1 ;j < m;j ++ )             // 循环个数
        {
            old
= p;
            p
= p -> next;
        }
        printf(
" %3d " ,p -> num);
        old
-> next = p -> next;
        free(p);
        p
= old -> next;
    }
    
return  p -> num;
}

你可能感兴趣的:(OS)