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

习题3.10 约瑟夫环 josephus问题

时间:2015-07-09 21:26:36      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
/* assume a header */
/* 双向循环链表 */
struct Node;
typedef struct Node * PtrToNode;
typedef PtrToNode List;
typedef PtrToNode position;

struct Node{
    PtrToNode Previous;
    PtrToNode Next;
    int Ele;
};
/* 删除双向循环链表中的元素例程 */
Position
Delete( Position p )
{
    Position tmp;
    tmp = p->next;
    p->Previous->Next = tmp;
    tmp->Previous = p->Previous;
    free( p );
    return tmp;
}
void
josephus( List L, int m, int n )
{
    int i,count = 0;
    Position p;
    p = L->Next;
    while( n > 1 )
    {
        count = m % n;
        for(i = 0; i < count; i++)
            p = p->Next;
        p = Delete( p );
        n--;
    }
    printf("%d",p->Ele);
}
View Code

L默认为双向循环链表,L为表头,Delete为删除双向链表结点的函数

整个表结构类似一个圆圈上面加一个表头

拓展:创建一个双向循环链表,以输入为0结束

技术分享
struct Node{
    PtrToNode Previous;
    PtrToNode Next;
    int Ele;
};
//创建一个双向循环链表
Position
CreateDoubleList( void )
{
   PtrToNode head,last,now;
   head = last = malloc( sizeof(struct Node ) );
   now = malloc( sizeof(strut Node ) );
   scanf("%d",&now->Ele);
   while(now->Ele != 0)
   {
       last->Next = now;
       now->Previous = last;
       last = now;
       now = malloc( sizeof( struct Node ) );
       scanf("%d",&now->Ele);
   }
   last->Next = head;
   head->Previous = last;
   free(now);
   return head;
}
View Code

创建一个单链表,类似

技术分享
//创建一个单向链表

struct Node{
    int data;
    PtrToNode Next;
};
Position
CreateSingleList( void )
{
    Position head,last,now;
    head = last = malloc( sizeof( struct Node ) );
    now = malloc( sizeof( struct Node ) );
    scanf("%d",&now->data);
    while(now->data != 0)
    {
        last->Next = now;
        last = now;
        now = malloc( sizeof( struct Node ) );
        scanf("%d",&now->data);
    }
    last->Next = NULL;
    free(now);
    return head;
}
View Code

 

习题3.10 约瑟夫环 josephus问题

标签:

原文地址:http://www.cnblogs.com/gabygoole/p/4634232.html

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